这是我在 mysql 中的查询:
SELECT school_id, first_name, last_name, email, blog_username, comment_username
FROM table
WHERE user_id IN (100, 3,72) ;
结果以升序显示两个 user_id。我怎样才能使它按照收到的顺序订购?
因此,3, 72, 100
我不希望结果是100, 3, 72
.
Select school_id, first_name, last_name, email, blog_username, comment_username
From table
Where user_id IN ( 100, 3, 72 )
Order By Case
When user_id = 100 Then 1
When user_id = 3 Then 2
When user_id = 72 Then 3
End Asc
补充说明:
正在寻求的是能够以自定义方式对行进行排序。换句话说,我们需要将自定义基数添加到一组不符合标准基数的值中。可以使用 Case 表达式来做到这一点。完成同样事情的另一种方法是:
Select school_id, first_name, last_name, email, blog_username, comment_username
From table
Join (
Select 100 As user_id, 1 As Sort
Union All Select 3, 2
Union All Select 72, 3
) As Seq
On Seq.user_id = table.user_id
Order By Seq.Sort
MySQL有一个FIELD()
适合这个的功能:
ORDER BY FIELD(user_id, 100, 3, 72 )
http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_field
和一般(方法是设计的,strings
但它可以很好地处理数字)
ORDER BY FIELD(field_name, value_1, value_2, ... )
然而
整个代码
SELECT school_id, first_name, last_name, email, blog_username, comment_username
FROM table
WHERE user_id IN (100, 3, 72)
ORDER BY FIELD(user_id, 100, 3, 72)
尽管我会考虑更改其余代码,因此您不必使用此方法。