Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 为1个值匹配2行的SQL查询_Mysql_Sql_Database - Fatal编程技术网

Mysql 为1个值匹配2行的SQL查询

Mysql 为1个值匹配2行的SQL查询,mysql,sql,database,Mysql,Sql,Database,如何编写查询,以查找一列中的2个特定值与另一列中的每1个值的匹配情况?我使用的是MySQL数据库 例如: | test_id | animal_type | classification_id | ---------------------------------------------- 1 cat 456 2 dog 456 3 mongoose 456

如何编写查询,以查找一列中的2个特定值与另一列中的每1个值的匹配情况?我使用的是MySQL数据库

例如:

| test_id | animal_type | classification_id |
----------------------------------------------
    1          cat             456
    2          dog             456
    3          mongoose        456
    4          cat             123
我想写一个查询,查找表中出现的同一动物类型的分类id为“123”和“456”的两行

如果我写了以下内容,它就不起作用了,因为我不知道如何在这个查询中包含animal_type

SELECT *
FROM test_table
WHERE classification_id = '123' AND classification_id = '456' 
如何编写查询以选择所有同时具有123和456作为特定动物类型分类id的行?

您可以使用:

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)
使用group by和have

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