2013-08-22 37 views
1

我有一個簡單的表:mysql命令由if條件 - 錯誤的順序

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 CASE WHEN type = 'short' THEN 2 ELSE RAND() * priority END AS prio, type, priority FROM test ORDER BY prio DESC, id DESC 
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 
+0

不使用ORDER BY 3當您更改列位置時,容易出錯...只是使用ORDER BY優先級 –

+0

在您的示例中,行總是按列'priority'排序。我想給'短'類型的普通隨機值,並根據其優先級爲每個'長'類型計算隨機值,然後按此值排序。 –