我有一张简单的表格:
CREATE TABLE `dev_a4a`.`test` ( `id` INT UNSIGNED NOT NULL
AUTO_INCREMENT , `type` VARCHAR(45) NOT NULL , `priority` INT NOT
NULL , PRIMARY KEY (`id`) );
以下行:
id|type |priority
1 |long |8
2 |long |3
3 |short|9
4 |short|1
我希望按条件排序行:
SELECT (RAND() * priority) as prio, type, priority FROM test
ORDER BY (IF(type = 'short', '2', prio)) DESC, id DESC
结果我得到的行没有按条件排序。每次看起来都是随机的。这是可能的结果之一:
prio | type | priority
'0.05013570194145264', 'long', '8'
'2.9015473750434326', 'long', '3'
'0.320064320527077', 'short', '1'
'7.598900996706356', 'short', '9'
我做错了什么?
预期结果:
prio | type | priority
'2.9015473750434326', 'long', '3' <- order by prio
'7.598900996706356', 'short', '9' <- order by common value 2
'0.320064320527077', 'short', '1' <- order by common value 2
'0.05013570194145264', 'long', '8' <- order by prio
答案 0 :(得分:0)
这个怎么样?
SELECT (RAND() * priority) as prio, type, priority ,CASE `type`
WHEN 'short' THEN 2
WHEN 'long' THEN 1
END AS t
FROM test
ORDER BY 3 DESC, id DESC
答案 1 :(得分:0)
好的,我解决了这个问题:
SELECT CASE WHEN type = 'short' THEN 2 ELSE RAND() * priority END AS prio, type, priority FROM test ORDER BY prio DESC, id DESC