不明白为什么我会得到这个 HAVING COUNT 的结果

can't understand why I am getting this result of HAVING COUNT

这是我的示例数据库:

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', 'cat'),
  ('3', 'fat', 'dog'),
  ('4', 'slim', 'dog'),
  ('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,因此列名不是一个好的选择。