选择WHERE Cast - 维护订单

时间:2016-06-18 17:14:59

标签: mysql

我想在这里维护字段的顺序。有什么想法吗?这会产生一个结果,但结果会以不同的顺序出现。

SELECT value FROM field_one WHERE cast(field_number as BINARY(6)) IN

(44,121.3,121.6,77,78,3,2.1,2.3,2.4,2.5) AND lead_id=1234 AND form_id=123

3 个答案:

答案 0 :(得分:2)

使用FIELD()功能进行自定义订单:

SELECT value FROM field_one WHERE cast(field_number as BINARY(6)) IN
(44,121.3,121.6,77,78,3,2.1,2.3,2.4,2.5) AND lead_id=1234 AND form_id=123
ORDER BY FIELD(cast(field_number as BINARY(6)), 44,121.3,121.6,77,78,3,2.1,2.3,2.4,2.5)

http://sqlfiddle.com/#!9/833ae4/7

答案 1 :(得分:1)

您需要在查询中指定order by子句。如果没有order by,则序列未定义。

SELECT value 
  FROM field_one 
 WHERE cast(field_number as BINARY(6)) IN (44,121.3,121.6,77,78,3,2.1,2.3,2.4,2.5) 
   AND lead_id=1234 
   AND form_id=123
 ORDER BY value

答案 2 :(得分:0)

如果您正在尝试维护IN子句中的值顺序,您可以像下面一样手动创建订单/等级,并使用您的表创建一个INNER JOIN,然后按手动创建的等级排序。

SELECT value 
FROM field_one 
INNER JOIN 
(SELECT 1 as rank, 44 as val UNION ALL
 SELECT 2 , 121.3 UNION ALL
 SELECT 3, 121.6 UNION ALL
 SELECT 4, 77 UNION ALL
 SELECT 5, 78 UNION ALL
 SELECT 6, 3 UNION ALL
 SELECT 7, 2.1 UNION ALL
 SELECT 8, 2.3 UNION ALL
 SELECT 9, 2.4 UNION ALL
 SELECT 10, 2.5)T
ON cast(field_number as BINARY(6)) = T.val
WHERE lead_id=1234 AND form_id=123
ORDER BY T.rank ASC