SQL选择语句

发布于 2024-10-12 10:04:46 字数 311 浏览 1 评论 0原文

我有一条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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烛影斜 2024-10-19 10:04:46

在 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 progressive ROW_NUMBER column and ask for a sort on that.

咿呀咿呀哟 2024-10-19 10:04:46
select * from users where username='bbb' 
UNION
select * from users where username='aaa' 
UNION
select * from users where username='ddd' 
UNION 
select * from users where username='ccc'

尽管该查询可能实现您希望的结果,正如用户 6502 所说,但该查询中的顺序仍然未指定,因此您不能安全地依赖它在不同的实现中返回。

另一方面,如果您的奇怪排序顺序并不重要,您应该只使用 WHERE IN 子句:

select * from users where username in ('aaa', 'bbb', 'ccc', 'ddd', 'ccc')
select * from users where username='bbb' 
UNION
select * from users where username='aaa' 
UNION
select * from users where username='ddd' 
UNION 
select * from users where username='ccc'

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:

select * from users where username in ('aaa', 'bbb', 'ccc', 'ddd', 'ccc')
落叶缤纷 2024-10-19 10:04:46

如果用户表中有一个“id”列(ddd 具有“最大 id”),那么您可以执行以下操作:

select * from users where username in ('aaa','bbb','ccc','ddd')
order by 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:

select * from users where username in ('aaa','bbb','ccc','ddd')
order by id;

ETA: If the id column is in another table, then you'll have to perform a join to get the correct ids.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文