簡體   English   中英

使用mysql按兩個字段對結果順序進行排序

[英]sort result order by two fields using mysql

現在,我正在嘗試從數據庫中獲取主題。

topics (
  `replied_at` int(11) unsigned DEFAULT NULL,
  `created_at` int(11) unsigned DEFAULT NULL,
)

我想按較大的replied_at或created_at對主題進行排序。因為我要獲取最新創建或回復的主題。

例如:

topic1:
replied_at: NULL
created_at: 1111

topic2:
replied_at: 2222
created_at: 0001

topic3:
replied_at: 3333
created_at: 1111

結果是:

topic3 topic2 topic1

mysql order by是否支持此查詢?

謝謝 :)

編輯:

我使用此查詢,但順序錯誤):

SELECT * FROM topic ORDER BY GREATEST(replied_at,created_at)desc limit 3 \\ G;

select * from `topics`
         order by greatest(coalesce(`replied_at`,0),coalesce(`created_at`,0)) desc;

或者,假設replied_at始終大於created_at

select * from `topics`
         order by coalesce(`replied_at`,`created_at`,0) desc;

使用GREATEST()

order by greatest(ifnull(replied_at,0), ifnull(created_at,0)) desc

暫無
暫無

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

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