以下是一个示例查询:
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;
现在,我们举个例子来说,我们有这些表:
用户:
+---------+-----------------------+
| user_id | email |
+---------+-----------------------+
| 1 | webmaster@example.com |
| 2 | admin@example.com |
+---------+-----------------------+
照片:
+---------+----------+
| user_id | photo_id |
+---------+----------+
| 1 | 1 |
| 1 | 2 |
+---------+----------+
上述查询的结果将形成以下结果:
+---------+-----------+
| user_id | photo_ids |
+---------+-----------+
| 1 | 1,2 |
| 2 | NULL |
+---------+-----------+
如何使它成为如果photo_ids列为NULL而不返回?
我试过了:
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;
但这会返回语法错误:
#1054 - Unknown column 'photo_ids' in 'where clause'
我已经尝试了HAVING
,因为我已经阅读了它与group_concat字段一起使用。
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;
结果: 您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得正确使用的语法' HAVING photo_ids IS NOT NULL'在第1行
答案 0 :(得分:1)
您可以在mysql中使用派生表并过滤掉以仅选择NOT NULL行。
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;
答案 1 :(得分:0)
试试这个MySQL查询: -
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;
答案 2 :(得分:0)
试试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