Refinement on Nested JOINs

So, I looked at the view that we have in our database, and it looks like a nested connection. I was wondering in which situations this practice would be useful.

In my specific example, it was used to connect to a table with a composite key, but only to connect to tables in which data is their primary key. For example, suppose a structure like this:

Activity(*IdActivity*, name)
Activity_Week(*IdActivity*, *WeekNo*, subject)
Attendance(*IdPerson*, *IdActivity*, *WeekNo*, isPresent)
Person(*IdPerson*, Name)

In this case, my query would look something like this:

SELECT p.Id, p.Name, COUNT(at.*) 
FROM Person p
INNER JOIN Activity a
  INNER JOIN Activity_Week aw 
    ON aw.IdActivity = a.IdActivity
  INNER JOIN Attendance at 
    ON at.IdActivity = a.IdActivity 
    AND at.WeekNo = aw.WeekNo
    AND at.isPresent = 1
  ON p.IdPerson = at.IdPerson
GROUP BY p.Id, p.Name

Thus, although in this situation I would doubt very much that this is useful (since you can just join the presence and cascade from there), is there another situation where such nested transitions are actually good or will it always be better to join the request?

, , , - :

SELECT p.Id, p.Name, COUNT(at.*) 
FROM Person p
INNER JOIN (
  SELECT a.name, at.* 
  FROM Activity a
  INNER JOIN Activity_Week aw 
    ON a.IdActivity = aw.IdActivity
  INNER JOIN Attendance at 
    ON at.IdActivity = a.IdActivity 
    AND at.WeekNo = aw.WeekNo
    AND at.isPresent = 1
) attendance_query ON p.IdPerson = attendance_query.IdPerson
GROUP BY p.Id, p.Name
+4

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


All Articles