MySQL 对结果进行排序以匹配 WHERE IN 表达式中值的顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6666152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Order results to match the order of values in a WHERE IN expression
提问by Aaron Lim
Is there a way I can make mysql return results from a Member database by the order I ask it by in the WHERE command?
有没有办法让 mysql 按照我在 WHERE 命令中询问的顺序从成员数据库返回结果?
SELECT *
FROM Members
WHERE MemberID = "6"
OR MemberId="3"
OR MemberID="5"
Currently it will return results ordered by MemberID ASC no matter what I do. I want it to return by 6,3,5 i.e. in the order that I ask it.
目前,无论我做什么,它都会返回按 MemberID ASC 排序的结果。我希望它在 6,3,5 之前返回,即按照我要求的顺序返回。
回答by Mchl
SELECT
*
FROM
Members
WHERE
MemberID IN ("6","3","5")
ORDER BY
FIELD(MemberID,"6","3","5");
回答by ADW
Select * from Members
WHERE MemberID = "6" or MemberId="3" or MemberID="5"
ORDER BY MemberID = "6" DESC, MemberId="3" DESC, MemberID="5" DESC;
回答by Sander Marechal
Try this:
尝试这个:
SELECT * FROM Members
ORDER BY CASE MemberId
WHEN 6 THEN 1
WHEN 3 THEN 2
WHEN 5 THEN 3
ELSE 999
END
回答by Kevin Burton
Try selecting the data using 3 UNION ALL
queries:
尝试使用 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"
or maybe you need to simply add a new column to hold the sort order ?
或者您可能需要简单地添加一个新列来保存排序顺序?
回答by Rahul
Try this
尝试这个
Select * from Members WHERE MemberID = "6" or MemberId="3" or MemberID="5" order by
MemberID = "6" desc
MemberId="3" desc
MemberID="5" desc
See this post once
看一次这个帖子
回答by Randy
no.
不。
you must specify an ORDER BY clause to get things into any repeatable order.
您必须指定 ORDER BY 子句才能将事物置于任何可重复的顺序中。
If you can construct some logic that specifies the order then you can include that in the ORDER BY otherwise, you cannot.
如果您可以构建一些指定顺序的逻辑,那么您可以将其包含在 ORDER BY 中,否则,您不能。
You may consider adding another data construct to map your 'random' values to a sequence or other ordering value, then using that.
您可以考虑添加另一个数据结构来将您的“随机”值映射到序列或其他排序值,然后使用它。