选择所有连接元素满足条件的元素

时间:2013-11-21 15:31:36

标签: sql

我发现很难用合适的标题来标记这个问题,但也许这就是因为我不知道如何实现我的目标。

我有以下数据库布局:

table:   folders
columns: folderId

table: files
columns: fileId, authorId

table: file_relation
columns: folderId, fileId

table: authors
columns: authorId, surname, firstName

我尝试实现的是列出仅包含作者X Y(姓氏= X,firstName = Y)的文件的所有文件夹。我的方法是这样的:

SELECT f.folderId FROM `folders` f 
     INNER JOIN `file_relation` rel ON rel.folderId = f.folderId 
     INNER JOIN `files` fls ON fls.fileId = rel.fileId 
     INNER JOIN `authors` a ON a.authorId = fls.authorId 
WHERE a.surname = X and a.firstName = Y;

现在列出了所有来自所述作者的文件的文件夹。但是,如果没有其他文件,我现在如何限制它们才被列出?

1 个答案:

答案 0 :(得分:1)

最好使用聚合函数而不是子查询。查询将如下所示:

SELECT f.folderId,
    COUNT(fls.fileId) as filesCount,
    SUM(a.surname = 'X' and a.firstName = 'Y') as authorFilesCount
FROM `folders` f 
     INNER JOIN `file_relation` rel ON rel.folderId = f.folderId 
     INNER JOIN `files` fls ON fls.fileId = rel.fileId 
     INNER JOIN `authors` a ON a.authorId = fls.authorId 
GROUP BY f.folderId
HAVING filesCount = authorFilesCount;