繁体   English   中英

如何在 MySQL 中使用 UNION 从多个表中查询数据

[英]How to query data from many tables using UNION in MySQL

我有 3 个表,想从table1&table2中获取 select 数据,然后从 table3 table3&table2 table2 中获取数据,最后,连接两个查询并获取结果的最后 10 个元素。
这些查询中的每一个都可以正常工作。 当我使用UNION时出现问题

SELECT t1.postID, 
       t1.status,
       t1.`number`, 
       t2.reference, 
       t2.joint_date
FROM table1 t1 
INNER JOIN table2 t2  ON t1.postID=t2.postID
WHERE t1.active=1 
AND t1.userID=3
ORDER BY t1.postID ASC
UNION
SELECT t3.postID, 
       t3.status,
       t3.`number`, 
       t4.reference, 
       t4.joint_date
FROM table3 t3
INNER JOIN table2 t4 ON t3.postID=t4.postID
WHERE t3.active=1 
AND t3.userID=3
ORDER BY t3.postID ASC
LIMIT 0, 5;

我只是收到一个错误。 我怎样才能通过一个查询来实现这一点?

在单个查询中组合UNIONORDER BYLIMIT时,重要的是要认识到ORDER BYLIMIT将应用于整个UNIONED结果集。 因此,我们只能在最终查询之后指定ORDER BYLIMIT

UNIONUNION ALL连接的查询中的ORDER BYLIMIT实际上并不是最后一个表达式的一部分,它们实际上是在它之后。 因此,您不能在ORDER BY中使用表别名,而只能使用在第一个表达式中定义的列别名,在第一个UNION之前。

如果您想从查询中获取最后10 条记录,那么我们可以简单地反转postID的顺序:

SELECT t1.postID, 
       t1.status,
       t1.`number`, 
       t2.reference, 
       t2.joint_date
FROM table1 t1 
INNER JOIN table2 t2  ON t1.postID=t2.postID
WHERE t1.active=1 
AND t1.userID=3
ORDER BY t1.postID ASC

UNION

SELECT t3.postID, 
       t3.status,
       t3.`number`, 
       t4.reference, 
       t4.joint_date
FROM table3 t3
INNER JOIN table2 t4 ON t3.postID=t4.postID
WHERE t3.active=1 
AND t3.userID=3

ORDER BY postID DESC
LIMIT 0, 10;

请注意,我故意在最后一个表达式和ORDER BY之间注入了一个空格,这是为了在视觉上突出显示此查询中的ORDER BYLIMITUNION的一部分,而不是第二个查询的一部分。 另请注意,我们确实需要(并且不能使用)表别名来引用postID列。

将联合的两半放入单独的元组中:

(SELECT t1.postID, t1.status, t1.`number`, t2.reference, t2.joint_date
 FROM table1 t1
 INNER JOIN table2 t2 ON t1.postID = t2.postID
 WHERE t1.active = 1 AND t1.userID = 3)
UNION
(SELECT t3.postID, t3.status, t3.`number`, t4.reference, t4.joint_date
 FROM table3 t3
 INNER JOIN table2 t4 ON t3.postID = t4.postID
 WHERE t3.active = 1 AND t3.userID = 3
 ORDER BY t3.postID
 LIMIT 0, 5)
ORDER BY postID;

请注意,最终的ORDER BY子句适用于联合完成后的整个结果集。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM