簡體   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