MySQL GROUP BY NULL and EMPTY

2020-07-18 07:10发布

问题:

In a MySQL query I am doing a GROUP BY with a text field. Due to the nature of the original data, some rows are contain empty strings for this field, and others are true null.

When grouping, how can I group empty string and null together, treating both as null?

回答1:

This can be accomplished by SELECT CASE. There may be a simpler way I do not know of.

The format of SELECT CASE is

SELECT
CASE
    WHEN table_name.text_field IS NULL OR table_name.text_field = ''
    THEN null
    ELSE table.text_field
END as new_field_name,
other_field, another_field, ...rest of query...

So you see, you can CASE together values with WHEN/THEN and default to the real value by ELSE.