mysql - UNION 查询不返回额外的列

标签 mysql join union

我有两个要合并的 SQL 查询,不幸的是我不是 MYSQL 的知识渊博的用户。

现在这是我的查询:

SELECT animal.species, count(animal.species) as f
FROM disp, animaldesc, animal 
WHERE disp.disp_id = animaldesc.disp_id 
AND animaldesc.authored = 1 
AND animaldesc.animal_id = animal.id 
GROUP BY animal.species 
union
SELECT animal.species, count(animal.species) as f_specific
FROM disp, animaldesc, animal 
WHERE disp.disp_id = animaldesc.disp_id 
AND animaldesc.authored = 1 
AND animaldesc.animal_id = animal.id 
AND disp.language = "en_gb" 
GROUP BY animal.species 
ORDER BY f DESC

此查询返回如下数据:

-----------------------|--------------------
species                | f
-----------------------|--------------------
M_A_1789               | 5
-----------------------|--------------------
M_A_1789               | 1
-----------------------|--------------------
M_A_1731               | 5
-----------------------|--------------------
M_A_1731               | 1

虽然我得到了我想要的所有数据,但结构是错误的。我相信这与使用 UNION 而不是 JOIN 有关。然而,我不确定要使用哪种类型的 JOIN(我猜是正确的),因为 f_specific 可以返回比 f 更少的行。

除了使用 UNION 方法之外,我找不到一个明确的解释来组合这两个查询?如何使用 JOIN 关键字以便我的查询返回以下内容:

-----------------------|------------|---------------
species                | f          | f_specific
-----------------------|------------|---------------
M_A_1789               | 5          |     1
-----------------------|------------|---------------
M_A_1731               | 5          |     1
-----------------------|------------|---------------

最好的问候。

最佳答案

您需要的查询是:

SELECT animal.species, 
    COUNT(animal.species) AS f, 
    SUM(IF(disp.language = "en_gb", 1, 0)) AS f_specific
FROM disp, animaldesc, animal 
WHERE disp.disp_id = animaldesc.disp_id 
    AND animaldesc.authored = 1 
    AND animaldesc.animal_id = animal.id 
GROUP BY animal.species 

这是来自您的 UNION 的第一个查询,它为 disp.language = 的每一行另外将 1 添加到 f_specific 'en_gb'。它应该返回您期望的结果集。

关于mysql - UNION 查询不返回额外的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549543/

相关文章:

azure - 在文档数据库中使用 JOIN 进行查询

sql - 在 MySQL 中转换 UNION 查询

php - php CMS 需要考虑哪些安全因素?

php - 为包括外键在内的整个模式转储 MySQL CREATE TABLE(创建顺序)

mysql - 连接两个表并求和计数记录

MySQL CONCAT '*' 符号向数据库 toast

MySQL 错误代码 1242

c# - 与 LINQ to XML 合并

mysql - 从每组涉及两个字段的方程式中选择最高值

javascript - 如何自动更新输出