我有两个表格:groups(group_id)
,member(group_id, name)
我希望选择组中的所有members
,其中每个人都有非空名称。例如,如果这是members
表:
group_id|name
1|a
1|b
2|c
2|null
3|null
3|null
然后查询结果应该返回:
group_id|name
1|a
1|b
我试过了
SELECT * FROM members M1
WHERE ALL(SELECT M2.name IS NOT NULL FROM members M2)
ORDER BY M1.group_id
但它没有用。
答案 0 :(得分:2)
使用bool_and()
:
select group_id, name
from members
where group_id in (
select group_id
from members
group by 1
having bool_and(name is not null)
);
答案 1 :(得分:1)
SELECT
*
FROM groups g
INNER JOIN members m
ON g.group_id = m.group_id
WHERE NOT EXISTS (SELECT * FROM members mbr WHERE mbr.name IS NULL AND mbr.group_id = m.group_id)
基本上,我们选择所有记录,除了那些我们可以找到具有相同组ID的空名称记录的记录。
请注意,我不相信这是SARG能力的,所以如果你有一个依赖于索引的海量数据库,这可能有点慢。
答案 2 :(得分:1)
如果您只需要分组并显示非空值,如何只是一个简单的
SELECT group_id, name FROM members
group by group_id, name
having name is not null and id = 1;
答案 3 :(得分:1)
另一种解决方案:
SELECT * FROM Table
WHERE group_id NOT IN (
SELECT group_id FROM table
WHERE name IS NULL
)