简体   繁体   English

MySQL有条件地在两个连接列上排序

[英]MySQL sort conditionally on two joined columns

I have a MySQL table structured with two date fields, like so: 我有一个MySQL表,结构有两个日期字段,如下所示:

uid int auto-increment
sponsor_name varchar
date_sent datetime
date_resent datetime

Let's assume data like: 我们假设数据如下:

(1, 'patrick', '2014-03-01 12:30:00', '0000-00-00 00:00:00' )
(2, 'patrick', '2014-03-05 14:30:00', '2014-03-18 00:30:00' )
(3, 'patrick', '2014-03-08 16:30:00', '2014-03-24 00:00:00' )
(4, 'patrick', '2014-03-20 12:30:00', '0000-00-00 00:00:00' )

When I run SELECT * FROM table ORDER BY date_resent DESC I see data returned as expected with the rows having some date_resent first, followed by those without: 当我运行SELECT * FROM table ORDER BY date_resent DESC我看到按预期返回的数据首先包含一些date_resent ,然后是没有的数据:

(3, 'patrick', '2014-03-08 16:30:00', '2014-03-24 00:00:00' )
(2, 'patrick', '2014-03-05 14:30:00', '2014-03-18 00:30:00' )
(1, 'patrick', '2014-03-01 12:30:00', '0000-00-00 00:00:00' )
(4, 'patrick', '2014-03-20 12:30:00', '0000-00-00 00:00:00' )

But what I want is to use some combination of both columns date_sent and date_resent , so that in the case date_resent is empty ('000-00-00 00:00:00') the date_sent is substituted in the ordering. 但我想要的是使用的列两者的某种组合date_sentdate_resent ,这样的情况下date_resent是空的(“000-00-00 00:00:00”)的date_sent进行排序取代。

The desired result would be data: 期望的结果将是数据:

(3, 'patrick', '2014-03-08 16:30:00', '2014-03-24 00:00:00' )
(4, 'patrick', '2014-03-20 12:30:00', '0000-00-00 00:00:00' )
(2, 'patrick', '2014-03-05 14:30:00', '2014-03-18 00:30:00' )
(1, 'patrick', '2014-03-01 12:30:00', '0000-00-00 00:00:00' )

What about: 关于什么:

SELECT * FROM table
ORDER BY IF(data_resent = '0000-00-00 00:00:00', data_sent, data_resent) DESC

Or if data_resent when not empty is always greater then data_sent (I guess it is), then you could try something like: 或者,如果data_resent非空时总是大于data_sent (我猜它是),那么你可以尝试类似:

SELECT * FROM table
ORDER BY GREATEST(data_sent, data_resent) DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM