2012-07-08 77 views
0

我有以下查詢具有相同的計數返回所有值

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

那麼查詢確實是得到一個人的身份證,讓他有寵物的所有名字,看起來在表中寵物爲同一人並檢查哪些寵物已被餵食多少次並輸出該人的身份證,寵物的名字以及餵食的頻率。

現在我只想輸出餵飽最多的寵物。我當然可以使用limit 1,但是我想輸出全部,如果餵食的數量對於幾隻寵物是相同的。

+0

'MAX(fed)'是我想你需要的。 – hjpotter92 2012-07-08 09:47:57

+0

什麼決定了寵物被餵食的次數?它是一列嗎?還是在寵物表中存在多少行?你可以發佈你的表格模式嗎? – 2012-07-08 09:49:06

+1

發佈它,因爲你的查詢是ambiguos。 – Samson 2012-07-08 09:50:49

回答

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 
) 
+0

這最近的問題基本上是相同的:http://stackoverflow.com/questions/11381674/sql-selecting-all-rows-with-maximum-值/ 11381856#11381856 – shawnt00 2012-07-08 09:56:41

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) 

左外連接將確保你從petLover返回所有結果,即使沒有餵食(即如果沒有餵食,你將返回所有寵物插圖)。如果您只需要飼餵動物的結果,請將其更改回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 
相關問題