2012-11-09 66 views
5

比方說,我有這樣的查詢:MySQL的GROUP BY 「和過濾器」

SELECT name, GROUP_CONCAT(number) 
FROM objects 
GROUP BY name 

,並將其輸出:

+----------+----------------------+ 
| NAME | GROUP_CONCAT(NUMBER) | 
+----------+----------------------+ 
| false_1 | 2,1     | 
| false_2 | 3,4     | 
| true_1 | 4,3,2,1    | 
| true_2 | 2,3     | 
+----------+----------------------+ 

現在,我怎麼能返回其2 AND 3number行?

注:此查詢分組 - 表有10行,像這樣:

+---------+--------+ 
| NAME | NUMBER | 
+---------+--------+ 
| true_1 | 1  | 
| true_1 | 2  | 
| true_1 | 3  | 
| ...  | ... | 
+---------+--------+ 

[Link to SQLFiddle]

回答

9
SELECT name, GROUP_CONCAT(number) 
FROM objects 
WHERE number IN (2,3) 
GROUP BY name 
HAVING COUNT(*) = 2 

,或者如果你想保留w的全部價值HICH名下有,

SELECT a.name, GROUP_CONCAT(A.number) 
FROM objects a 
     INNER JOIN 
     (
      SELECT name 
      FROM objects 
      WHERE number IN (2,3) 
      GROUP BY name 
      HAVING COUNT(*) = 2 
     ) b ON a.Name = b.Name 
GROUP BY a.name 
+1

第一個工程就像一個魅力!謝謝! – Kristian

+1

不客氣@Kristian! :D –

+0

爲什麼行'true_1 | 4,3,2,1'不會以其形式返回。 –