使用mysql按两个字段排序结果顺序

时间:2013-09-24 11:07:43

标签: 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是否通过支持此查询来订购?

谢谢:)

编辑:

我使用此查询但订单错误):

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

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:1)

使用GREATEST()

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