MySQL GROUP BY 不是空行

标签 mysql sql group-by

我有一个返回的查询:

uid  | text    | flag | nonuid | another_id
123  | "tree"  | 1    | 176    | 7098
456  | "apple" | 1    | 321    | 9686
321  | "apple" | 0    |        | 5675
847  | "tree"  | 1    | 176    | 6456
993  | "car"   | 1    | 332    | 9686
222  | "cat"   | 0    |        | 7098
913  | "car"   | 0    |        | 2301
176  | "tree"  | 0    |        | 6456
982  | "car"   | 1    | 332    | 7098
332  | "car"   | 0    |        | 7321

uid: unique field for every record
text: not unique piece of text
flag: whenever this is a "repost" entry of another row
nonuid: uid of the original of the repost
another_id: process_id that created the entry

我需要“折叠这个列表,让nonuid在列表中只出现一次。如果该字段为空,则没有转发,所以应该显示整行。所以之后运行“正确的”查询我应该看到相同的列表:

uid  | text    | flag | nonuid | another_id: GROUP_CONCAT(another_id)
123  | "tree"  | 1    | 176    | 7098,6456
456  | "apple" | 1    | 321    | 9686
321  | "apple" | 0    |        | 5675
993  | "car"   | 1    | 332    | 9686,7098
222  | "cat"   | 0    |        | 7098
993  | "car"   | 0    |        | 9686
176  | "tree"  | 0    |        | 6456
332  | "car"   | 0    |        | 7321

我可以通过textGROUP BY列表,但是uid332uid 222 有相同的文字,但都不是转贴 - 我应该保留原件和转贴。或者我可以通过 nonuid 崩溃,这也失败了,因为所有“空的”nonuid 都组合在一起。

最佳答案

为什么不在您需要的两列上都使用 GROUP BY

SELECT `text`, `nonuid`, GROUP_CONCAT( `another_id`)
FROM yourTable
GROUP BY `text`, `nonuid`;

Example Fiddle

你没有指定,如何选择其他列,所以我在这里省略了

关于MySQL GROUP BY 不是空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21705917/

相关文章:

sql-server - Group By 中的按位运算

mysql - 将sql查询的结果写入mysql中的文件

java - 是否可以创建由现有 HBase 表支持的 Phoenix 表?

SQL Server 计算列的元数据

grails - 有关网域中listsize的Grails标准

mysql - MYSQL 中的计数乘以行并按日期和 ID 进行过滤

mysql - 在 2 个表中插入值,其中第二个表需要第一个表中的 ID

mysql - 如何选择不在另一个表中的映射数据

php - 检查数据库列中是否存在部分字符串

sql - 旋转数据库表