我有一个按日期差异排序的查询。我的排序目前正在工作,但我想使用案例如
如果priority<=10 THEN 10
将添加当前优先级
我的查询当前返回修改优先级值的默认异常值
我的查询是
SELECT videoid,priority,
CASE WHEN priority<=10 THEN (priority+10)
WHEN priority>10 and priority<=20 THEN (priority+9)
WHEN priority<=30 THEN (priority+8)
END AS 'modified_priority',
DATEDIFF(CURDATE(),
DATE(from_unixtime(submittime))) AS d
FROM
`datatable`
ORDER BY d
答案 0 :(得分:4)
你的最后一个案例与所有人相匹配试试这个
SELECT videoid,priority,
CASE WHEN priority <=10 THEN (priority+10)
WHEN priority>10 and priority <=20 THEN (priority+9)
WHEN priority>20 AND priority <=30 THEN (priority+8)
END AS `modified_priority`,
DATEDIFF(CURDATE(),
DATE(from_unixtime(submittime))) AS d
FROM
`datatable`
ORDER BY d
答案 1 :(得分:3)
按顺序处理Case语句,返回第一个匹配条件。您可以使用此优势并将语句简化为:
SELECT videoid, priority,
(CASE WHEN priority <= 10 THEN (priority+10)
WHEN priority <= 20 THEN (priority+9)
WHEN priority <= 30 THEN (priority+8)
END) AS modified_priority,
DATEDIFF(CURDATE(), DATE(from_unixtime(submittime))) AS d
FROM `datatable`
ORDER BY d;
如果您不希望返回NULL
的优先级值大于30,那么您需要一个ELSE
子句。也许:
SELECT videoid, priority,
(CASE WHEN priority <= 10 THEN (priority+10)
WHEN priority <= 20 THEN (priority+9)
WHEN priority <= 30 THEN (priority+8)
ELSE priority
END) AS modified_priority,
DATEDIFF(CURDATE(), DATE(from_unixtime(submittime))) AS d
FROM `datatable`
ORDER BY d;
另外,我从modified_priority
左右删除了单引号。您应该只对字符串和日期常量使用单引号。