簡體   English   中英

從兩個表中選擇具有不同字段名稱的時間戳,然后對其排序?

[英]Select timestamps with different field names from two tables, and order them?

我在這里查看了其他一些問題,但找不到與我匹配的解決方案。 我不太了解其中的某些部分,因此無法適應他們的問題。

我有一張這樣的桌子:

post_id, post_author, post_message, post_timestamp, post_threadpost_id, post_author, post_message, post_timestamp, post_thread thread_id, thread_author, thread_message, thread_timestamp ,我想從兩個(不同的)表中獲取*,並按其時間戳排序,以便從兩者中獲取最新的。

我該如何實現? 正如我說的,我在這里研究了其他一些解決方案,但無法適應我所找到的解決方案,它們的時間戳字段名稱相同。

提前致謝。

您將要使用從線程到帖子的LEFT JOIN ,並且可以使用coalesce進行排序。 性能可能會很糟糕,但是讓我們先進行一些工作,然后對其進行調整。

SELECT p.*, t.*, coalesce(p.post_timestamp, t.thread_timestamp) as timestamp FROM thread t
LEFT JOIN (SELECT * FROM post ORDER BY post_timestamp DESC LIMIT 1) as p on p.post_thread = t.thread_id
ORDER BY timestamp DESC
LIMIT 10
;

coalesce函數采用參數列表,並返回第一個非null的參數。 因此,在這種情況下,它將返回發布時間戳,除非沒有發布,在這種情況下,它將返回線程時間戳。 該聯接是LEFT聯接,因此,即使子選擇返回零結果,仍然會有一個結果行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM