问题描述
这是我的示例数据库:
CREATE TABLE IF NOT EXISTS `animals` (
`id` int(6) unsigned NOT NULL,`condition` varchar(200) NOT NULL,`animal` varchar(200) NOT NULL,PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `animals` (`id`,`condition`,`animal`) VALUES
('1','fat','cat'),('2','slim',('3','dog'),('4',('5','normal','dog');
我正在发出以下请求:
SELECT result.condition FROM
(
SELECT * FROM animals WHERE animal = 'cat'
UNION
SELECT * FROM animals WHERE animal = 'dog'
) as result
并达到我的期望:
condition
---------
fat
slim
fat
slim
normal
现在,我只想获取具有重复项的值。 我通过添加最后一行来修改我的请求:
SELECT result.condition FROM
(
SELECT * FROM animals WHERE animal = 'cat'
UNION
SELECT * FROM animals WHERE animal = 'dog'
) as result
HAVING COUNT(result.condition) > 1
但是我的实际结果是:
condition
---------
fat
我想得到:
condition
---------
fat
slim
请告诉我我在做什么错
P.S。 我的请求的这一部分无法更改。
SELECT * FROM animals WHERE animal = 'cat'
UNION
SELECT * FROM animals WHERE animal = 'dog'
我正在简化实际请求,但主要思想仍然是:由于2个请求的UNION,我得到了一列值。
P.P.S。我不是在寻找最有效的请求,而是在寻找更容易理解的内容
解决方法
不需要union
。只需过滤,汇总和having
:
select `condition`
from animals
where animal in ('cat','dog')
group by `condition`
having count(*) > 1
如果您确实想要union
,则需要在外部查询中使用group by
子句以使查询成为有效的聚合查询:
SELECT `condition`
FROM (
SELECT * FROM animals WHERE animal = 'cat'
UNION ALL
SELECT * FROM animals WHERE animal = 'dog'
) as result
GROUP BY `condition`
HAVING COUNT(*) > 1
旁注:condition
在MySQL中是a reserved word,因此列名不是一个好的选择。