简体   繁体   English

SQL - where 子句中的连接字符串未按预期工作 - Redshift

[英]SQL - concatenated string in where clause not working as expected - Redshift

This is the SQL (Redshift) I am referring to:这是 SQL (Redshift) 我指的是:

SELECT * 
  FROM table_a
 WHERE col_a||col_b NOT IN 
            (
                SELECT col_a||col_b 
                  from table_b
            );

There are values in table_a which don't exist in table_b, yet this always evaluates to a No rows. table_a 中有一些值在 table_b 中不存在,但这总是评估为无行。

Any insight?有什么见解吗?

Use NOT EXISTS , not NOT IN !!!使用NOT EXISTS ,而不是NOT IN !!! NOT IN will return no rows at all if any value in the subquery is NULL .如果子查询中的任何值为NULL ,则NOT IN将根本不返回任何行。 Plus, you are comparing multiple columns by concatenating them.另外,您通过连接它们来比较多个列。 That is likely to be a bad method because of collisions: ab/c matches a/bc.由于冲突,这可能是一个不好的方法:ab/c 匹配 a/bc。

So use this:所以使用这个:

SELECT a.* 
FROM table_a a
WHERE NOT EXISTS (SELECT 1
                  FROM table_b b
                  WHERE b.col_a = a.col_a AND b.col_b = a.col_b
                 );

The sub query might be having a null value, which is failing the not in clause.子查询可能具有 null 值,这使 not in 子句失败。

Use coalesce to replace null with an appropriate value based on your data.根据您的数据,使用 coalesce 将 null 替换为适当的值。 I have used a ~ character in place of null我使用 ~ 字符代替 null

SELECT * 
  FROM table_a
 WHERE col_a||col_b NOT IN 
            (
                SELECT coalesce (col_a,'~')||coalesce (col_b , '~')
                  from table_b
            );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM