所以,我正在查看我们在数据库中的视图,并且似乎有一个嵌套的联结。我想知道在什么情况下练习会有用。
在我的具体示例中,它曾用于与具有复合键的表连接,但仅与以数据作为主键的表连接。例如,假设一个这样的结构:
Activity(*IdActivity*, name)
Activity_Week(*IdActivity*, *WeekNo*, subject)
Attendance(*IdPerson*, *IdActivity*, *WeekNo*, isPresent)
Person(*IdPerson*, Name)
在这种情况下,我的查询看起来像:
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
因此,在这种情况下,我会高度怀疑它是否有用(因为你可以简单地加入出勤和级联),是否有任何其他情况,这样的嵌套连接实际上是一件好事,或者最好是加入一个请求呢?
加入请求的意思是:
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