简体   繁体   English

MySQL; GROUP BY 但仅当列不为空时

[英]MySQL; GROUP BY but only if column is not empty

I have the following SQL query:我有以下 SQL 查询:

SELECT * FROM my_table GROUP BY B,D,F;

If there are some rows where B is empty and D is empty AND F is empty, it'll grouped to a single row where all the three columns are empty.如果有一些行B为空且D为空且F为空,则它将分组为一行,其中所有三列均为空。

But instead I want: in case all three columns (B, D, F) of a row are empty don't group this row show it.但相反,我想要:如果一行的所有三列(B、D、F)都是空的,请不要将此行分组显示。

Means: If I have the following:意思是:如果我有以下内容:

在此处输入图像描述

result should be:结果应该是:

在此处输入图像描述

How can I do this?我怎样才能做到这一点?

Firstly, you are selecting * with group by !! 首先,您选择*与分组依据! not sure if this is going to work with you. 不知道这是否适合您。

Anyway, to achieve what you want try this 无论如何,要实现您想要的效果,请尝试此操作

SELECT B,D,F
FROM your_table
WHERE NOT (B='' AND D='' AND F='')
GROUP BY B,D,F

UNION ALL

SELECT B,D,F
FROM your_table
WHERE B='' AND D='' AND F=''

try尝试

SELECT * FROM my_table GROUP BY B,D,F,IF((B="" AND D="" AND F=""),id,0);

assuming that id is a unique key.假设 id 是唯一键。

if any of the columns you want to group by aren't empty, zero is retuned instead of id, but if all three ARE empty, then id is returned, and thus ones with all three others empty are no longer grouped.如果您要分组的任何列不为空,则返回零而不是 id,但如果所有三个都是空的,则返回 id,因此不再对其他三个都为空的列进行分组。

And yes, this works with select *.是的,这适用于 select *。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM