将NOT IN查询转换为LEFT JOIN

时间:2016-08-31 10:58:47

标签: sql left-join netezza

适应Netezza数据库我需要转换fallowing查询(因为Netezza不支持NOT IN(SUBQUERY)):

UPDATE table1 t1 SET t1.deal_type=t2.deal_type 
FROM  table2 t2
WHERE t1.id_col=t2.id_col 
AND t1.price=t2.price
AND t1.id_col2=t2.id_col2
AND t2.price NOT IN (
  SELECT st1.price
  FROM table1 st1, table2 st2
  WHERE st1.id_col=st2.id_col 
  AND st1.price=st2.price
  AND st1.id_col2=st2.id_col2
  AND st1.id_col=t1.id_col
  AND t2.deal_type=st2.deal_type
  GROUP BY st1.id_col, st1.price, st1.id_col2, st2.deal_type
  HAVING COUNT (*)>1);

我尝试使用LEFT JOIN但未返回所有记录:

UPDATE table1 t1 SET t1.deal_type = t2.deal_type
FROM table2 t2 
LEFT JOIN 
   (SELECT st1.price, st1.id_col, st2.deal_type
   FROM table1 st1, table2 st2
   WHERE st1.id_col=st2.id_col 
   AND st1.price=st2.price
   AND st1.id_col2=st2.id_col2
   GROUP BY st1.id_col, st1.price, st1.id_col2, st2.deal_type
   HAVING COUNT (*)>1) subq ON (subq.id_col=t1.id_col
   AND t2.deal_type=subq.deal_type)
WHERE 
 t1.id_col=t2.id_col 
 AND t1.price=t2.price
 AND t1.id_col2=t2.id_col2
 subq.price is null

我错了的任何建议。或NETEZZA不支持任何其他工作方式。不支持女巫

2 个答案:

答案 0 :(得分:1)

我认为您忘记将价格添加到左连接条件。

如果此ID和类型有重复但价格不同, NOT-IN条件将通过,但Left-Join(IS NULL)条件将失败

只需更改

ON (subq.id_col=t1.id_col
   AND t2.deal_type=subq.deal_type)

ON (subq.id_col=t1.id_col
  AND t2.deal_type=subq.deal_type)
  AND subq.price=t2.price)

答案 1 :(得分:0)

如果netezza支持EXISTS并且您的第一个查询在逻辑上正确

,请试试这个
UPDATE t1 SET t1.deal_type=t2.deal_type 
FROM  table1 t1
INNER JOIN table2 t2 ON t1.id_col=t2.id_col 
    AND t1.price=t2.price
    AND t1.id_col2=t2.id_col2
LEFT JOIN ( SELECT st1.id_col
        FROM table1 st1
        INNER JOIN table2 st2 ON st1.id_col=st2.id_col 
            AND st1.price=st2.price
            AND st1.id_col2=st2.id_col2
            AND t2.deal_type=st2.deal_type
        GROUP BY st1.id_col, st1.price, st1.id_col2, st2.deal_type
        HAVING COUNT (*)>1) i ON i.id_col=t1.id_col
WHERE i.id_col IS NULL