php MySQL ORDER BY IN()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1332434/
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
MySQL ORDER BY IN()
提问by Henk Denneboom
I have a PHP array with numbers of ID's in it. These numbers are already ordered.
我有一个包含 ID 编号的 PHP 数组。这些号码已经被订购了。
Now i would like to get my result via the IN() method, to get all of the ID's.
现在我想通过 IN() 方法获得我的结果,以获取所有 ID。
However, these ID's should be ordered like in the IN method.
但是,这些 ID 应该像在 IN 方法中一样排序。
For example:
例如:
IN(4,7,3,8,9)
Should give a result like:
应该给出如下结果:
4 - Article 4
7 - Article 7
3 - Article 3
8 - Article 8
9 - Article 9
Any suggestions? Maybe there is a function to do this?
有什么建议?也许有一个功能可以做到这一点?
Thanks!
谢谢!
回答by Alex Martelli
回答by deceze
You could use FIELD():
你可以使用FIELD():
ORDER BY FIELD(id, 3,2,5,7,8,1)
Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.
返回 str 在 str1, str2, str3, ... 列表中的索引(位置)。如果没有找到 str 则返回 0。
It's kind of an ugly hack though, so really only use it if you have no other choice. Sorting the output in your app may be better.
不过,这有点丑陋,所以只有在别无选择的情况下才真正使用它。在您的应用程序中对输出进行排序可能会更好。
回答by paxdiablo
Standard SQL does not provide a way to do this (MySQL may, but I prefer solutions that are vendor-neutral so I can switch DBMS' at any time).
标准 SQL 不提供执行此操作的方法(MySQL 可以,但我更喜欢供应商中立的解决方案,以便我可以随时切换 DBMS)。
This is something you should do in post-processing afterthe result set is returned. SQL can only return them in an order specified in the "order by" clause (or in anyorder if there's no such clause).
这是你在返回结果集后的后处理中应该做的事情。SQL 只能按照“order by”子句中指定的顺序(或者如果没有这样的子句,则以任何顺序)返回它们。
The other possibility (though I don't like it, I'm honor-bound to give you the choice) is to make multiple trips to the database, one for each ID, and process them as they come in:
另一种可能性(虽然我不喜欢它,我很荣幸地给你选择)是多次访问数据库,每个 ID 一个,并在它们进来时处理它们:
select * from tbl where article_id = 4;
// Process those.
select * from tbl where article_id = 7;
// Process those.
: : : : :
select * from tbl where article_id = 9;
// Process those.
回答by Oliver Friedrich
You'll just need to give the correct order by statement.
您只需要按语句给出正确的顺序。
SELECT ID FROM myTable WHERE ID IN(1,2,3,4) ORDER BY ID
Why would you want to get your data ordered unordered like in your example?
为什么要像示例中那样对数据进行无序排序?
If you don't mind concatening long queries, try that way:
如果您不介意连接长查询,请尝试这种方式:
SELECT ID FROM myTable WHERE ID=1
UNION
SELECT ID FROM myTable WHERE ID=3
UNION
SELECT ID FROM myTable WHERE ID=2

![PHP MYSQL $row[$variable]](/res/img/loading.gif)