GROUP BY - do not group NULL(GROUP BY - 不要将 NULL 分组)
问题描述
我正在尝试找出一种使用 group by 函数返回结果的方法.
I'm trying to figure out a way to return results by using the group by function.
GROUP BY 按预期工作,但我的问题是:是否可以通过忽略 NULL 字段来创建组.这样它就不会将 NULL 组合在一起,因为我仍然需要指定字段为 NULL 的所有行.
GROUP BY is working as expected, but my question is: Is it possible to have a group by ignoring the NULL field. So that it does not group NULLs together because I still need all the rows where the specified field is NULL.
SELECT `table1`.*,
GROUP_CONCAT(id SEPARATOR ',') AS `children_ids`
FROM `table1`
WHERE (enabled = 1)
GROUP BY `ancestor`
所以现在假设我有 5 行并且祖先字段为 NULL,它返回我 1 行......但我想要所有 5 行.
So now let's say I have 5 rows and the ancestor field is NULL, it returns me 1 row....but I want all 5.
推荐答案
也许您应该向空列添加一些内容以使它们独一无二并以此为基础进行分组?我正在寻找某种序列来代替 UUID() ,但这可能也能正常工作.
Perhaps you should add something to the null columns to make them unique and group on that? I was looking for some sort of sequence to use instead of UUID() but this might work just as well.
SELECT `table1`.*,
IFNULL(ancestor,UUID()) as unq_ancestor
GROUP_CONCAT(id SEPARATOR ',') AS `children_ids`
FROM `table1`
WHERE (enabled = 1)
GROUP BY unq_ancestor
这篇关于GROUP BY - 不要将 NULL 分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:GROUP BY - 不要将 NULL 分组


- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01