如何在 MySQL GROUP BY 子句中排序或选择行?

发布于 2024-09-27 09:39:32 字数 501 浏览 0 评论 0原文

我有一个像这样的表:

id       number    otherfields
-------------------------------------------
664      48       aaa
665      49       bbb
666      55       ccc
667      48       ddd

我的查询按 number 字段进行分组,我希望它选择第一个(最低的)id,以便数据像 < code>ccc,aaa,bbb(按数字排序时)。然而我得到了 ccc,ddd,bbb - 换句话说,它为数字 48 选择行 #667 而不是 #664。

奇怪的是,这只发生在实时服务器上;在本地主机上,即使表完全相同(从本地主机导出,导入到服务器上),我也以正确的方式得到它。

是否可以确保 GROUP BY 子句选择第一个 ID?

I have a table like this:

id       number    otherfields
-------------------------------------------
664      48       aaa
665      49       bbb
666      55       ccc
667      48       ddd

My query groups by the number field, and I want it to pick the first (lowest) id, so that the data comes out like ccc,aaa,bbb (when ordered by number). However I'm getting ccc,ddd,bbb - in other words, it's picking row #667 instead of #664 for the number 48.

Oddly, this only happens on the live server; on localhost I get it the correct way even though the table is exactly the same (exported from localhost, imported onto server).

Is it possible to ensure that the GROUP BY clause picks the first ID?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

暮色兮凉城 2024-10-04 09:39:32

不,这在 MySQL 中是不可能的。您必须使用联接。

SELECT id, number, otherfields FROM table 
  WHERE id in (SELECT min(id) FROM table GROUP BY number)

No, it is not possible in MySQL. You have to use a join.

SELECT id, number, otherfields FROM table 
  WHERE id in (SELECT min(id) FROM table GROUP BY number)
自在安然 2024-10-04 09:39:32

SQL-92 版本。

SELECT 
     id, number, otherfields 
FROM 
     table t
     join (SELECT min(id) as id, number FROM table GROUP BY number) sq --subquery
       on t.id = sq.id

SQL-92 version.

SELECT 
     id, number, otherfields 
FROM 
     table t
     join (SELECT min(id) as id, number FROM table GROUP BY number) sq --subquery
       on t.id = sq.id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文