Sql Querying, group relationships

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 know that my SQL syntax is not correct :) I hope this is clear enough. My problem is this: I want to download the group entry and all GroupMember entries associated with this group. As I see, there are two options.

One request:

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 that it is only one trip through the database, but has the disadvantage of returning redundant data (all group data is duplicated for each member of the group)

The second solution does not return duplicate data, but includes two round trips to the database.

? , , , , , . ?

,

+3
7

, , , . SQL- . sql, , , ​​DB.

+3

, .

. , .

, , .

+2

- , . , , .

+1

, , .

, .

, , , , .

, , ,

  • . . , . , , .

  • Lazy Loading - , Lazy Loading. , , . , , .

0

SQL (, SQL Server 2005).

, Group, .

- , , , , where (, , ), .

0

, , , .

insatnce, , , , , .

, , , , , , , .

( ), .

0

In such a simple request, I would try to execute it in a single request. The overhead of two database calls is likely to exceed the extra SQL processing time from the query.

The UNION proposal will do it for you:

SELECT id, someData1, someData2 
FROM Group 
WHERE id = 4
UNION 
SELECT id, someData, null 
FROM GroupMember 
WHERE group_id = 4; 
-2
source

Source: https://habr.com/ru/post/1744787/


All Articles