[英]Fetch posts from different tables order by time
我有4個mysql表,即post_type1
, post_type2
, post_type3
和post_type4
。 這4個表的編號不同。 列和不同結構。 它們中'id'
常見列是'id'
即主鍵)和“時間(datetime)”(即撰寫文章的時間)。 如果我要從表中獲取最后10個帖子,我可以執行以下操作:
SELECT * FROM post_type1 ORDER BY time DESC LIMIT 10
但是,如果我想獲得最后10個帖子,無論它們屬於哪個4表,該怎么辦?
我想到的一個想法非常低效,即從每個表中獲取10條記錄(共40條記錄),然后使用php進行合並排序並獲取前10條記錄。 有什么有效的方法可以做到這一點嗎? 我真的很堅持。 提前致謝。
使用UNION
合並它們。 由於它們具有不同的列,因此您需要在子查詢中為缺少的列添加占位符。
SELECT *
FROM (
SELECT "post_type1" AS tablename, id, time, col1, col2, NULL AS col3, col4, col5
FROM post_type1
ORDER BY time DESC LIMIT 10
UNION
SELECT "post_type2" AS tablename, id, time, col1, NULL, col3, col4, NULL
FROM post_type2
ORDER BY time DESC LIMIT 10
UNION
SELECT "post_type3" AS tablename, id, time, NULL, col2, col3, col4, col5
FROM post_type3
ORDER BY time DESC LIMIT 10
UNION
SELECT "post_type4" AS tablename, id, time, col1, col2, col3, NULL, NULL
FROM post_type4
ORDER BY time DESC LIMIT 10
)
ORDER BY time DESC
LIMIT 10
確保所有表在time
列上都有索引:
ALTER TABLE post_type1 ADD INDEX (time)
為什么選擇10個用戶? 我認為合並也不是一個好主意。 我認為最好使用@Barmar編寫的UNION並將結果放入數組中。 然后,您可以使用陣列進行任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.