Sql Querying, group relationships

Posted by Jordan on Stack Overflow See other posts from Stack Overflow or by Jordan
Published on 2010-05-10T14:49:04Z Indexed on 2010/05/10 14:54 UTC
Read the original article Hit count: 498

Filed under:

Hi, Suppose I have two tables:

Group
(
    id integer primary key,
    someData1 text,
    someData2 text
)

GroupMember
(
    id integer primary key,
    group_id   foreign key to Group.id,
    someData   text
)

I'm aware that my SQL syntax is not correct :) Hopefully is clear enough. My problem is this: I want to load a group record and all the GroupMember records associated with that group. As I see it, there are two options.

A single query:

SELECT Group.id, Group.someData1, Group.someData2 GroupMember.id, GroupMember.someData
FROM Group INNER JOIN GroupMember ...
WHERE Group.id = 4;

Two queries:

SELECT id, someData2, someData2
FROM Group
WHERE id = 4;

SELECT id, someData
FROM GroupMember
WHERE group_id = 4;

The first solution has the advantage of only being one database round trip, but has the disadvantage of returning redundant data (All group data is duplicated for every group member)

The second solution returns no duplicate data but involves two round trips to the database.

What is preferable here? I suppose there's some threshold such that if the group sizes become sufficiently large, the cost of returning all the redundant data is going to be greater than the overhead involved with an additional database call. What other things should I be thinking about here?

Thanks, Jordan

© Stack Overflow or respective owner

Related posts about sql