在SubQuery Comparison中包含NULL值

时间:2014-04-23 12:10:48

标签: mysql sql join

我有一个子查询查询。

SELECT
        last_name,
        hire_date,
        salary,
        commission_pct
    FROM employees 
    WHERE
        salary IN
            (
                SELECT
                        salary
                    FROM employees
                    WHERE last_name='kochhar'
            )
        AND last_name <> 'Kochhar'
        AND commission_pct IN
            (
                SELECT
                        commission_pct
                    FROM employees
                    WHERE last_name='kochhar'
            );

问题在于,我的数据库包含在commission_pct中包含NULL的条目。而kochhar的委托_pct也是无效的。

但是在运营商中没有将其包含在结果中。什么可以解决这个问题?

3 个答案:

答案 0 :(得分:0)

使用您从不使用的替代值,例如-1:

  and coalesce(commission_pct,-1) in
  ( 
    select coalesce(commission_pct,-1) 
    from employees 
    where last_name='kochhar'
  );

或使用存在:

  and exists
  ( 
    select *
    from employees x
    where x.last_name='kochhar'
    and 
    (
      x.commission_pct = employees.commission_pct
      or
      (x.commission_pct is null and employees.commission_pct is null)
    )
  );

答案 1 :(得分:0)

如果您希望将两个exists值视为相同,请使用NULL和更复杂的逻辑:

select last_name, hire_date, salary, commission_pct
from employees e
where salary in (select salary from employees where last_name='kochhar') and
      last_name <> 'Kochhar' and
      exists (select 1
              from employees e2
              where last_name = 'kochhar' and
                    (e2.commission_pct = e.commission_pct or
                     e2.commission_pct is null and e.commission_pct is null
                    )
              );

如果您正在对多个字段进行比较,我建议使用join而不是where子句中的一系列条件:

select last_name, hire_date, salary, commission_pct
from employees e join
     employees k
     on k.last_name = 'kochhar' and e.last_name <> 'kochhar' and
        e.salary = k.salary and
        (e.commission_pct = k.commission_pct or
         e.commission_pct is null and k.commission_pct is null
        );

答案 2 :(得分:0)

您可以使用IFNULL函数来处理NULL值并指定默认值。然后,值将正确匹配,如下所示:

SELECT
        last_name,
        hire_date,
        salary,
        commission_pct
    FROM employees 
    WHERE
        salary IN
            (
                SELECT
                        salary
                    FROM employees
                    WHERE last_name='kochhar'
            )
        AND last_name <> 'Kochhar'
        AND IFNULL(commission_pct, 0) IN
            (
                SELECT
                        IFNULL(commission_pct, 0)
                    FROM employees
                    WHERE last_name='kochhar'
            );

您也可以考虑重新编写查询以获得更好的效果,正如其他回答者所建议的那样。

参考:

Control Flow Functions on MySQL Reference Manual