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

MYSQL Union All not returning all record by two merging 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;

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

你的结果意味着 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 子句适用于 整个 联合查询,这意味着它将 return 只是一个单条记录。