2013-09-24 51 views
0

现在我正在尝试从我的数据库中获取主题。使用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标题2 TOPIC1

支持请问mysql命令此查询?

谢谢:)

编辑:

我用这个查询,但我得到了错误的顺序):

SELECT * FROM主题ORDER BY GREATEST(replied_at,created_at)递减极限3 \ G;

回答

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; 
+0

假设replied_at总是大于created_at !!好主意:)谢谢 – Felix

+0

但是,如果我使用这个查询,我该如何添加索引?我应该为这种类型创建一个新字段(latest_update)吗? – Felix

1

使用GREATEST()

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

谢谢:)它使用IFNULL后的作品。 – Felix