2017-10-06 55 views
1

我該如何編寫一個查詢來查找哪一個列中的每個值爲1的2個特定值匹配的位置?我正在使用MySQL數據庫。用於1值的SQL查詢匹配2行

例如:

| test_id | animal_type | classification_id | 
---------------------------------------------- 
    1   cat    456 
    2   dog    456 
    3   mongoose  456 
    4   cat    123 

我想編寫發現2行碰巧具有「123」和「456」一個classification_id對於相同animal_type查詢哪裏,表中出現。

如果我寫下以下它不起作用,因爲我不知道如何在此查詢中包含animal_type。

SELECT * 
FROM test_table 
WHERE classification_id = '123' AND classification_id = '456' 

我該如何編寫一個查詢來選擇同時具有123和456作爲特定animal_type的classification_id的所有行?

回答

3

你可以使用:

SELECT animal_type 
FROM test_table 
WHERE classification_id IN (123, 456) 
GROUP BY animal_type 
HAVING COUNT(DISTINCT classification_id) = 2; 

如果你需要整行:

SELECT * 
FROM test_table 
WHERE animal_type IN (SELECT animal_type 
         FROM test_table 
         WHERE classification_id IN (123, 456) 
         GROUP BY animal_type 
         HAVING COUNT(DISTINCT classification_id) = 2) 
0
SELECT count(test_id) as animal_count,test_table.* 
FROM test_table 
WHERE classification_id = '123' AND classification_id = '456' 
GROUP BY animal_type HAVING animal_count > 2 

使用GROUP BY和HAVING。