订购结果以匹配WHERE IN表达式中的值顺序

时间:2011-07-12 14:50:55

标签: mysql sql

有没有办法让mysql按照我在WHERE命令中询问的顺序从成员数据库返回结果?

SELECT * 
FROM Members 
WHERE MemberID = "6" 
OR MemberId="3" 
OR MemberID="5"

目前,无论我做什么,它都会返回由MemberID ASC订购的结果。我希望它以6,3,5返回,即按我要求的顺序返回。

6 个答案:

答案 0 :(得分:32)

SELECT 
  * 
FROM 
  Members 
WHERE 
  MemberID IN ("6","3","5")
ORDER BY 
  FIELD(MemberID,"6","3","5");

答案 1 :(得分:16)

Select * from Members
WHERE MemberID = "6" or MemberId="3" or MemberID="5"
ORDER BY MemberID = "6" DESC, MemberId="3" DESC, MemberID="5" DESC;

答案 2 :(得分:4)

试试这个:

SELECT * FROM Members
ORDER BY CASE MemberId
    WHEN 6 THEN 1
    WHEN 3 THEN 2
    WHEN 5 THEN 3
    ELSE 999
END

答案 3 :(得分:1)

尝试使用3个UNION ALL查询选择数据:

SELECT * FROM Members WHERE MemberID = "6"
UNION ALL
SELECT * FROM Members WHERE MemberId = "3"
UNION ALL
SELECT * FROM Members WHERE MemberID = "5"

或者您可能需要简单地添加一个新列来保存排序顺序?

答案 4 :(得分:1)

试试这个

Select * from Members WHERE MemberID = "6" or MemberId="3" or MemberID="5" order by 
MemberID = "6" desc 
MemberId="3" desc
MemberID="5" desc

查看此帖子一次

How to make MYSQL query results ORDER BY conditions order?

答案 5 :(得分:0)

没有

您必须指定一个ORDER BY子句才能使事物进入任何可重复的顺序。

如果你可以构造一些指定顺序的逻辑,那么你可以在ORDER BY中包含它,否则就不能。

您可以考虑添加另一个数据构造,将“随机”值映射到序列或其他排序值,然后使用它。