我有兩個查詢選擇相似的列,但有不同的WHERE
和JOIN
子句。我需要將這兩個查詢與UNION
合併,以便總共顯示26個結果(合併),按日期排序。我不知道我會如何處理以下兩個查詢。結合兩個不同的查詢
首先查詢:
SELECT p.post_id,
p.reply_to,
p.parent_id,
p.post_path,
p.user_id,
p.content,
p.datetime,
p.total_likes,
p.total_replies,
p.total_reposts,
u.username,
u.display_name,
l.like_id,
l.user_id
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON (l.post_id = p.post_id AND l.user_id = ?)
WHERE p.user_id IN (SELECT following_id FROM follows WHERE user_id = ?)
AND p.removed != 1
ORDER BY p.datetime DESC LIMIT 26
第二個查詢:
SELECT p.post_id,
p.reply_to,
p.parent_id,
p.post_path,
p.user_id,
p.content,
p.datetime,
p.total_likes,
p.total_replies,
p.total_reposts,
u.username,
u.display_name,
l.like_id,
l.user_id
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON l.post_id = p.post_id
WHERE l.user_id IN (SELECT user_id FROM likes WHERE user_id IN (SELECT following_id FROM follows WHERE user_id = ? AND following_id != ?))
AND l.user_id != p.user_id AND p.removed != 1
ORDER BY p.datetime DESC LIMIT 26
我會怎麼做呢?
他們有相同的一組返回列?看起來像它一樣。只需在兩次選擇之間放下'UNION'(用於刪除dups)或'UNION ALL'。 – Andrew
只是使用union all作爲andrew所說的並在查詢結束時使用'ORDER BY p.datetime DESC LIMIT 26'確保它在末尾使用一次 –