2016-03-26 33 views
0

我有一個表,測試,與屬性中:ID水果SQL集團通過屬性,顯示的結果,如果有多於一個組

我們在說表中的下列內容:

id, fruits 

1, Apple 
2, Banana 
3, Apple 

我想一個查詢組,這些由水果(一組蘋果,香蕉在另一個)和回報,如果有多於1該組。

因此,對於上面的例子中,查詢應該返回:

1, Apple 
3, Apple 

這是我到目前爲止有:

SELECT * 
FROM testing 
GROUP BY 'fruits' 
    HAVING COUNT(*) > 1 
ORDER BY 'id' 

此查詢僅返回蘋果之一。

感謝您的幫助! Toby。

回答

1

您可以使用子查詢找到重複的,而且得到你的行外查詢;

SELECT * FROM testing 
WHERE fruits IN (
    SELECT fruits FROM testing 
    GROUP BY fruits HAVING COUNT(*)>1 
) 
ORDER BY id 

An SQLfiddle to test with

1

你必須加入回到談判桌,以得到期望的結果:

SELECT t1.* 
    FROM testing AS t1 
    JOIN (
     SELECT fruits 
     FROM testing 
     GROUP BY fruits 
     HAVING COUNT(*) > 1 
    ) AS t2 ON t1.fruits = t2.fruits 
    ORDER BY t1.id 
2

其實,最有效的方法,這樣做可能是使用exists

select t.* 
from testing t 
where exists (select 1 
       from testing t2 
       where t2.fruits = t.fruits and t2.id <> t.id 
      ); 

爲了獲得最佳性能,你想在testing(fruits, id)的索引。

+0

請你看看[我的問題](http://stackoverflow.com/questions/36246530/how-can-i-put-a-condition-on-the-way-of-join)?說實話,我問我的問題只是爲了看看你的意見*。 – stack