如何订购或选择MySQL GROUP BY子句中的行?

编程入门 行业动态 更新时间:2024-10-27 00:28:05
本文介绍了如何订购或选择MySQL GROUP BY子句中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的表:

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

我的查询按 number 字段,我希望它选择第一个(最低) id ,以便数据像 ccc,aaa,bbb (当由 number 命令时)。然而,我得到了 ccc,ddd,bbb - 换句话说,它选择的行数为#667而不是#664。

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

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

解决方案

在MySQL中。你必须使用连接。

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

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?

解决方案

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)

更多推荐

如何订购或选择MySQL GROUP BY子句中的行?

本文发布于:2023-10-14 22:47:14,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:句中   MySQL   GROUP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!