【问题标题】:can't understand why I am getting this result of HAVING COUNT不明白为什么我会得到 HAVING COUNT 的结果
【发布时间】:2020-10-08 19:16:44
【问题描述】:

这是我的示例数据库:

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

请告诉我我做错了什么。

附: 这部分是我的请求,无法更改。

SELECT * FROM animals WHERE animal = 'cat'
UNION
SELECT * FROM animals WHERE animal = 'dog'

我正在简化我的实际请求,但主要思想仍然存在:由于 2 个请求的 UNION,我得到了一列值。

附言我不是在寻找最有效的请求,我在寻找更容易理解的内容

【问题讨论】:

    标签: sql group-by count union having


    【解决方案1】:

    不需要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,因此不适合作为列名。

    【讨论】:

    • 正如我所说,我正在简化我的实际请求,但主要思想仍然存在:由于 2 个请求的 UNION,我得到了一列值。事实上,这些请求要复杂得多。
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多