如何编写查询以查找另一列中每1个值在一列中的2个特定值匹配的位置?我正在使用MySQL数据库。
例如:
| test_id | animal_type | classification_id |
----------------------------------------------
1 cat 456
2 dog 456
3 mongoose 456
4 cat 123
我想编写一个查询,在查询表中出现的情况下,发现两行碰巧有一个“123”和“456”的分类,用于相同的animal_type。
如果我写下面的内容不起作用,因为我不知道如何在此查询中包含animal_type。
SELECT *
FROM test_table
WHERE classification_id = '123' AND classification_id = '456'
如何编写查询以选择同时包含123和456作为特定animal_type的classification_id的所有行?
答案 0 :(得分: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)
答案 1 :(得分: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。