您发布的查询不会运行;您需要按 id、nameOfPet 分组。这是个人偏好,但我也会指定您的联接(以使其更具可读性并且更容易在联接类型之间进行更改):
SELECT id, nameOfPet, COUNT(p.fed)
FROM petLover pl
LEFT OUTER JOIN pets p ON pl.nameOfPet = p.nameOfPet
WHERE id = 180
GROUP BY id, nameOfPet
ORDER BY COUNT(p.fed)
LEFT OUTER JOIN 将确保您从 petLover 返回所有结果,即使没有喂食(即,如果没有喂食,您将返回所有 petLovers)。如果您只想要动物喂食后的结果,请将其更改回 INNER JOIN。这是一个修改后的查询,用于执行您要查找的内容(基于行):
SELECT pl.id, pl.nameOfPet, COUNT(*)
FROM petLover pl
LEFT OUTER JOIN pets p ON pl.nameOfPet = p.nameOfPet
GROUP BY pl.id, pl.nameOfPet
HAVING COUNT(*) >= ALL (
SELECT COUNT(*)
FROM petLover pl
LEFT OUTER JOIN pets p ON pl.nameOfPet = p.nameOfPet
GROUP BY pl.id, pl.nameOfPet
)
ORDER BY COUNT(*) DESC
编辑
除了原始评论中我的问题的答案之外,您应该能够执行以下操作来修改上面的 SQL:
SELECT pl.id, pl.nameOfPet, SUM(p.fed)
FROM petLover pl
LEFT OUTER JOIN pets p ON pl.nameOfPet = p.nameOfPet
GROUP BY pl.id, pl.nameOfPet
HAVING SUM(p.fed) >= ALL (
SELECT SUM(p.fed)
FROM petLover pl
LEFT OUTER JOIN pets p ON pl.nameOfPet = p.nameOfPet
GROUP BY pl.id, pl.nameOfPet
)
ORDER BY SUM(p.fed) DESC