什么是处理空值的最优雅的方法

时间:2014-01-02 09:54:29

标签: mysql sql

我有两个表,以及一个类似于::

的查询
select * from table_1
where x.column_1 in (
    select column_2 from table_2
    where column_3 = 'foo')

这几乎对我有用; column_1column_2中有空格我希望被视为匹配。

我可以写一个union

-- query above
union all
select * from table_1
where column_2 is null
and exists (select * from table_2
    where column_3 = 'foo'
    and column_2 is null)

但是会扫描每个表两次,这似乎效率低下。

有没有办法将两个查询结合起来进行有效的mire查询?

4 个答案:

答案 0 :(得分:2)

试试这个

select * from table_1
where coalesce (column_1,'special value') in 
      (
        select coalesce (column_2,'special value') 
          from table_2
         where column_3 = 'foo'
      )

当然'special value'不应该包含在column_3的{​​{1}}中,并且必须与列的数据类型兼容。

答案 1 :(得分:2)

这不适合你吗?

select  *   
from    table_1 t1
where   EXISTS (
                    select  1
                    from    table_2 t2
                    where   t2.column_3 = 'foo'
                    AND     (
                                    t1.column_1 = t2.column_2
                                OR  (t1.column_1 IS NULL AND t2.column_2 IS NULL)
                            )
                )

这将包括它们相等或两者都是NULL。

我避免ISNULL, IFNULL, COALESCE的原因是@alzaimar所述,数据类型和特殊值问题

修改

正如@ypercube所提到的,这可以简化为MySQL

select  *   
from    table_1 t1
where   EXISTS (
                    select  1
                    from    table_2 t2
                    where   t2.column_3 = 'foo'
                    AND     t1.column_1 <=> t2.column_2                
                 )

答案 2 :(得分:0)

试试这个

select T.* from table_1 T

LEFT JOIN table_2 S ON T.column_1 = S.column_2 OR NULLIF(T.column_1,NULL) = NULLIF(S.column_2 ,NULL)

where column_3 = 'foo'

答案 3 :(得分:0)

试试这个:

SELECT * 
FROM   table_1 t1 
       INNER JOIN table_2 t2 
               ON t1.column_1 = t2.column_2 
WHERE  t2.column_3 = 'foo' 
       AND t1.column_2 IS NULL 
       AND t2.column_2 IS NULL