MYSQL Union All 不通过两个合并查询返回所有记录

Posted

技术标签:

【中文标题】MYSQL Union All 不通过两个合并查询返回所有记录【英文标题】:MYSQL Union All not returning all record by two merging query 【发布时间】:2020-12-08 06:08:53 【问题描述】:
SELECT tah.project_id_new as "project_id", tah.history_createdon from task_audit_history tah 
where task_id=64 and project_id != project_id_new;

Result

SELECT tah.project_id as "project_id", tah.history_createdon from task_audit_history tah 
where task_id=64 ORDER BY history_createdon asc limit 1;

Result

When I tried to combined above two queries using UNION ALL it return only one record. Why ? i mean it 
should include all record from two query.

SELECT tah.project_id_new as "project_id", tah.history_createdon from task_audit_history tah 
where task_id=64 and project_id != project_id_new UNION ALL SELECT tah.project_id as "project_id", tah.history_createdon from task_audit_history tah 
where task_id=64 ORDER BY history_createdon asc limit 1;

Query result

【问题讨论】:

显示第三个查询的精确 SQL 文本。 下次请将结果作为文本粘贴到此处,而不是链接到图像。在这里阅读原因:meta.***.com/questions/285551/… 【参考方案1】:

您的结果意味着 ORDER BYLIMIT 子句被应用于整个联合查询,而不仅仅是子查询(这是您想要的行为)。尝试使用这个版本:

(SELECT tah.project_id_new AS project_id, tah.history_createdon
 FROM task_audit_history tah 
 WHERE task_id = 64 AND project_id != project_id_new)
UNION ALL
(SELECT tah.project_id AS project_id, tah.history_createdon
 FROM task_audit_history tah 
 WHERE task_id = 64
 ORDER BY history_createdon
 LIMIT 1);

为了完整起见,以下查询可能是您最初运行的结果,结果可能只有一行:

SELECT tah.project_id_new AS project_id, tah.history_createdon
FROM task_audit_history tah 
WHERE task_id = 64 AND project_id != project_id_new
UNION ALL
SELECT tah.project_id AS project_id, tah.history_createdon
FROM task_audit_history tah 
WHERE task_id = 64
ORDER BY history_createdon
LIMIT 1;

在这种情况下,ORDER BYLIMIT 子句适用于整个联合查询,这意味着它将只返回一条记录。

【讨论】:

以上是关于MYSQL Union All 不通过两个合并查询返回所有记录的主要内容,如果未能解决你的问题,请参考以下文章

MySQL使用UNION ALL将两个查询合并成一个结果

mysql合并查询(多张表) union 和 union all

Mysql联合查询union和union all的使用介绍

请教:SQL同一数据库中,两个查询结果数据类型不同时的union all 合并问题

Mysql联合查询UNION和UNION ALL的使用介绍

Mysql联合查询UNION和UNION ALL的使用介绍