Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP_CONCAT return NULL if any value is NULL

How can I make GROUPT_CONCAT return NULL if any column is NULL?

Here is a test table:

CREATE TABLE gc (
  a INT(11) NOT NULL,
  b VARCHAR(1) DEFAULT NULL
);

INSERT INTO gc (a, b) VALUES
(1, 'a'),
(1, 'b'),
(2, 'c'),
(2, NULL),
(3, 'e');

And my query:

SELECT a, GROUP_CONCAT(b)
FROM gc
GROUP BY a;

This is what I get:

a | GROUP_CONCAT(b)
--+----------------
1 | a,b
2 | c
3 | e

This is what I want:

a | GROUP_CONCAT(b)
--+----------------
1 | a,b
2 | NULL
3 | e
like image 653
Petah Avatar asked Aug 23 '12 23:08

Petah


1 Answers

In an IF expression check if any value is NULL in the group. I can think of a couple of ways of doing that:

1) Count the non-null values and compare it to the number of rows in the group:

SELECT a, IF(COUNT(b) = COUNT(*), GROUP_CONCAT(b), NULL) AS bs
FROM gc
GROUP BY a

See it working online: sqlfiddle

2) Count the number of null values using SUM:

SELECT a, IF(SUM(b IS NULL) = 0, GROUP_CONCAT(b), NULL) AS bs
FROM gc
GROUP BY a

See it working online: sqlfiddle

like image 177
Mark Byers Avatar answered Sep 23 '22 14:09

Mark Byers