MESTQL ORDER BY TIMESTAMPDIFF如果有两列

时间:2017-06-29 11:57:30

标签: mysql sql

我在查询中排序时遇到了一些问题。

所以,我需要首先显示表中当前时间和列之间的差异(remind_date)必须是(-70 - 0)ASC  如果remindDAteDIFf不在我的范围内而不是命令按status_updated DESC在其他情况下按顺序排列(status_updated)DESC。

我写了这个查询:

SELECT TIMESTAMPDIFF(MINUTE,remind_date, NOW()) as remindDAteDIFf,
order_id, remind_date, status_id, status_updated 
FROM s_order
ORDER BY IF(remindDAteDIFf BETWEEN -70 AND 0, remind_date, status_updated) DESC;

所以我得到了下一个结果enter image description here

哪个好,但我需要ASC和status_updated BY DESC排序字段remindDAteDIFf。 (第一次需要显示提醒DAteFf = -16和-28) 我试过了

IF(remindDAteDIFf BETWEEN -70 AND 0, remind_date ASC, status_updated DESC) 

但我有错误,说查询是不正确的

3 个答案:

答案 0 :(得分:0)

我认为您需要order by中的三个键:

ORDER BY (remindDAteDIFf BETWEEN -70 AND 0) DESC,  -- put these first
         (CASE WHEN remindDAteDIFf BETWEEN -70 AND 0 THEN remind_date END) ASC,
         status_updated DESC;

第一把钥匙放在"最近"价值第一。第二个订单仅由remind_date订购。第三个按status_updated排序其余部分。

答案 1 :(得分:0)

试试这个,使用减号与desc

相反
ORDER BY IF(
    remindDAteDIFf BETWEEN -70 AND 0,
    0 - unix_timestamp(remind_date),
    unix_timestamp(status_updated)) DESC;

答案 2 :(得分:0)

我找到解决方案:

IF(remindDateDiff BETWEEN -70 AND 0, remindDateDiff, -71) DESC , status_updated DESC