用途:
SELECT u.userid,
u.username,
COALESCE(f.numFiles, 0) AS numFiles,
COALESCE(p.numPhotos, 0) AS numFiles,
COALESCE(g.numGroups, 0) AS numGroups
FROM [USER] u
LEFT JOIN (SELECT t.userid,
COUNT(*) AS numFiles
FROM [FILES] t
GROUP BY t.userid)f ON f.userid = u.userid
LEFT JOIN (SELECT t.userid,
COUNT(*) AS numPhotos
FROM [PHOTOS] t
GROUP BY t.userid) p ON p.userid = u.userid
LEFT JOIN (SELECT t.userid,
COUNT(*) AS numGroups
FROM [GROUPS] t
GROUP BY t.userid) g ON g.userid = u.userid
WHERE u.userid = 2
您必须在一个查询中使用外部联接;所有表的内部联接都要求用户在结果集中的文件、照片和组表中至少有一条记录。外部联接意味着至少有一个表(文件、照片或组)中的记录的用户将被返回。
但加入也会使结果集膨胀,这是我之前版本答案中出现的问题。通过将查询更改为对文件、组和照片计数使用派生表/内联视图,解决了问题,并且不需要在派生表/内联视图之外进行分组。