SQL SELECT行,其他列的行为null

时间:2012-08-19 19:00:32

标签: mysql sql

首先,如果标题令人困惑,请抱歉 SQL不是我的强项,而且我已经在这方面工作了一段时间,我对mmoment的想法是加入的,也可能是小组。

索托示例:

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组成。

我只想要'type'行'WHERE key1不为null且key2不为null。

因此,在记录3中,类型1具有空键,因此我希望类型1的所有记录都不包含在派生表中。

1 个答案:

答案 0 :(得分: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