Reputation: 16212
Here's an example query:
SELECT u.user_id,
(SELECT GROUP_CONCAT(photo_id)
FROM photos p WHERE p.user_id = u.user_id)
AS photo_ids FROM users u;
Now, lets say for example purposes we have these tables:
Users:
+---------+-----------------------+
| user_id | email |
+---------+-----------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+---------+-----------------------+
Photos:
+---------+----------+
| user_id | photo_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
+---------+----------+
The results of the query above would form these results:
+---------+-----------+
| user_id | photo_ids |
+---------+-----------+
| 1 | 1,2 |
| 2 | NULL |
+---------+-----------+
How can I make it so that if the photo_ids column is NULL that it isn't returned?
I've tried:
SELECT u.user_id,
(SELECT GROUP_CONCAT(photo_id)
FROM photos p WHERE p.user_id = u.user_id)
AS photo_ids FROM users u
WHERE photo_ids IS NOT NULL;
but this returns a syntax error:
#1054 - Unknown column 'photo_ids' in 'where clause'
I've also tried HAVING
as I've read it works with group_concat fields.
SELECT u.user_id,
(SELECT GROUP_CONCAT(photo_id)
FROM photos p WHERE p.user_id = u.user_id)
AS photo_ids FROM users u
HAVING photo_ids IS NOT NULL;
RESULT: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'HAVING photo_ids IS NOT NULL' at line 1
Upvotes: 0
Views: 610
Reputation: 3
Try this MySQL query :-
SELECT u.user_id,
(SELECT GROUP_CONCAT(photo_id)
FROM photos p WHERE p.user_id = u.user_id)
AS photo_ids FROM users u
WHERE photo_ids IS NOT NULL;
Upvotes: 0
Reputation: 6661
Try right join
:-
select Users.user_id,GROUP_CONCAT(photo_id) as photo_ids
from Users right join Photos
on Users.user_id=Photos.user_id group by Users.user_id
Upvotes: 0
Reputation: 36671
You can use derived table in mysql and filter out to select only NOT NULL rows.
select * from
(
SELECT u.user_id,
(SELECT GROUP_CONCAT(photo_id)
FROM photos p WHERE p.user_id = u.user_id)
AS photo_ids FROM users u
) as DT
where DT.photo_ids not null;
Upvotes: 1