SQL选择语句
我有一条SQL语句:
SELECT *
FROM users
WHERE username = 'bbb'
OR username = 'aaa'
OR username = 'ddd'
OR username = 'ccc'
表中ddd的最大id比ccc比bbb比aaa。
现在,当它返回结果时,它总是按 id 对它们进行排序,例如:aaa、bbb、ccc、ddd。 但我希望它们保持与我输入的顺序相同,例如:bbb、aaa、ddd、ccc。
有人可以帮我解决吗?
I have an SQL Statement:
SELECT *
FROM users
WHERE username = 'bbb'
OR username = 'aaa'
OR username = 'ddd'
OR username = 'ccc'
In the table ddd has the biggest id than ccc than bbb than aaa.
Now when it returns the results it always sorts them by the id like:aaa, bbb, ccc, ddd.
But i want them to remain in the same order i entered them like: bbb, aaa, ddd, ccc.
Can someone help me with a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 SQL 中,检索顺序是未指定的,除非您使用
ORDER BY
请求。如果您想保留输入的顺序,请添加一个渐进的ROW_NUMBER
列,并要求对其进行排序。In SQL the order of retrieval is unspecified unless you ask for it with
ORDER BY
. If you want to keep the order you entered them then add a progressiveROW_NUMBER
column and ask for a sort on that.尽管该查询可能实现您希望的结果,正如用户 6502 所说,但该查询中的顺序仍然未指定,因此您不能安全地依赖它在不同的实现中返回。
另一方面,如果您的奇怪排序顺序并不重要,您应该只使用 WHERE IN 子句:
Despite the fact that this query may achieve what you wish, as user 6502 stated, the order is still unspecified in this query, and therefore you can't safely depend on it to be returned as such across different implementations.
As another side note, if your strange sort order didn't matter, you should just use a WHERE IN clause:
如果用户表中有一个“id”列(ddd 具有“最大 id”),那么您可以执行以下操作:
ETA:如果 id 列位于另一个表中,则您必须执行加入以获得正确的 ID。
If you have an "id" column in the users table (with ddd having the "biggest id"), then you can do something like this:
ETA: If the id column is in another table, then you'll have to perform a join to get the correct ids.