查询以选择没有特定字段的所有元素

时间:2018-04-21 16:03:30

标签: mysql sql select

首先我使用的是mysql 5.6

我想选择至少满足其中一个请求的所有元素:

  1. 是否有某个字段。
  2. 某个字段的空值(对于空,我的意思是:len(trim(value)) == 0
  3. 我会做一个更明确的例子

    table2
    id|field|value
    1 |x    |12
    1 |y    |23
    1 |z    |34
    2 |x    |45
    2 |y    |56
    2 |z    |  <---- is an empty string with 0/1 spaces
    3 |x    |67
    

    所以我想要的是例如,如果我想要所有没有字段z的字段我应该获得(2,3) 如果所有字段都没有y,我应该获得(3

    这是我试过的但没有取得多大成功:

    SELECT t12.id 
    FROM table2 AS t12
    WHERE NOT IN ( 
        SELECT t2.id 
        FROM table2 as t2
        WHERE t2.field = 'y' 
            AND t2.value <> '' AND t2.value IS NOT NULL
    )
    

1 个答案:

答案 0 :(得分:0)

select id from t group by id
having min(len(value)) = 0 or count(case when field = 'x' then 1 end) = 0

如果必须通过单行而不是整个组来满足条件,则在case中合并多个条件。