0

我有以下查询

select id, nameOfPet, count(fed)
from petLover, pets
where id = 180 and petLover.nameOfPet = pets.nameOfPet
group by fed
order by fed desc;

因此,查询所做的是获取一个人的 id,获取他拥有的所有宠物的名称,在表中查找同一个人的 pets,并检查哪个宠物已经喂了多少次,然后输出这个人的 id,即宠物的名字宠物以及喂食的频率。

现在我只想输出喂得最多的宠物。我当然可以使用limit 1,但如果几只宠物的喂食次数相同,我想全部输出。

4

2 回答 2

2

嵌套查询派生了计数。除了只有一列之外,它与最外面的查询相同。

select id, nameOfPet, count(fed)
from petLover, pets
where id = 180 and petLover.nameOfPet = pets.nameOfPet
group by fed
having count(fed) >= ALL (
    select count(fed)
    from petLover, pets
    where id = 180 and petLover.nameOfPet = pets.nameOfPet
    group by fed
)
于 2012-07-08T09:55:55.630 回答
0

您发布的查询不会运行;您需要按 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
于 2012-07-08T10:07:34.650 回答