我想要一个查询,它会为我提供ID与其他项目匹配的所有项目,其中匹配项目组大于X.
假设我有两个表,提交和submission_items。每个提交都有一个submission_id,每个submission_item都有一个外键,即父提交的submission_id。提交可以有多个submission_items。
我希望获得包含超过X submission_items的所有提交内容。
我试过了:
select submissions.*, submission_item.*
from submission
join submission_item ON submissions.submission_id = submission_item.submission_id
group by submission.submission_id
having count(*) > 1
它错误地说它想要GROUP BY功能中的其他字段。我怎样才能更好地做到这一点?
答案 0 :(得分:1)
当您指定GROUP BY时,SELECT语句中的字段必须是group子句的一部分或聚合的一部分。
您需要找到您感兴趣的ID,然后将其重新加入表格。
SELECT * FROM
submission si INNER JOIN
(select submission_id
from submission
join submission_item ON submissions.submission_id = submission_item.submission_id
group by submission.submission_id
having count(*) > 1) c
ON si.submission_id = c.submission_id
或者您可以单独对所有字段进行分组
select submissions.submission_id, submissions.x, submissions.y
from submission
join submission_item ON submissions.submission_id = submission_item.submission_id
group by submission.submission_id, submissions.x, submissions.y
having count(*) > 1