首先,如果标题令人困惑,请见谅。
SQL 不是我的强项,我已经在这方面工作了一段时间,我现在的想法是连接,也许还有组。
索托示例:
record | type | key1 | key2 | data1
---------------------------------------
1 | 1 | joe | smoe | 10
2 | 2 | homer | simpson | 20
3 | 1 | null | null | 30
4 | 3 | bart | simpson | 40
其中主键由id、key1、key2组成。
我只想要“类型”行,其中 key1 不为空且 key2 不为空。
因为在记录 3 中,类型 1 具有空键,因此我希望所有类型 1 的记录不包含在派生表中。
最佳答案
这是一个相关的、“不存在”的方法:
select *
from T as t1
where not exists (
select *
from T as t2
where t2.type = t1.type and (t2.key1 is null or t2.key2 is null)
)
这是一个使用非相关查询和分组的查询。也许这就是您的想法:
select *
from T as t1
where t1.type in (
select t2.type
from T as t2
group by t2.type
having count(*) = count(t2.key1) and count(*) = count(t2.key2)
)
自从我了解 mysql 查询计划可能对这些事情很敏感。这是与连接等效的:
select t1.*
from T as t1
inner join
(
select t2.type
from T as t2
group by t2.type
having count(*) = count(t2.key1) and count(*) = count(t2.key2)
) as goodtypes
on goodtypes.type = t1.type
关于mysql - SQL SELECT 行,其中其他地方的列行为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12029127/