比较同一个表中的值集

时间:2017-10-24 17:59:18

标签: sql postgresql

我正在尝试比较同一个表中的两组数据以验证更新操作。我已创建此查询以并排查看不同的信息集,但是当我在WHERE子句中添加其他约束时,我返回零行。

以下查询向我展示了彼此相邻的两个记录集,因此我可以看到有不同的componentid s:

WITH src AS 
     (SELECT id AS s_id,
             moduleid AS s_moduleid, 
             instanceid AS s_instanceid, 
             tagid AS s_tagid, 
             componentid AS s_componentid 
      FROM component_junction WHERE id=103)
SELECT * FROM component_junction cj 
JOIN src ON s_moduleid=cj.moduleid 
         AND s_instanceid=cj.instanceid 
         AND s_tagid=cj.tagid 
WHERE cj.id=117

返回:

id  | moduleid | instanceid | tagid | componentid | s_id | s_moduleid | s_instanceid | s_tagid | s_componentid
----|----------|------------|-------|-------------|------|------------|--------------|---------|--------------
117 | 2923     | 7179       | 1     |   <null>    | 103  | 2923       | 7179         | 1       | <null>
117 | 2923     | 7179       | 2     |   <null>    | 103  | 2923       | 7179         | 2       | <null>
117 | 2924     | 1404       | 1     |   <null>    | 103  | 2924       | 1404         | 1       | <null>
117 | 2924     | 1404       | 2     |   <null>    | 103  | 2924       | 1404         | 2       | <null>
117 | 1        | 41         | 2     |   <null>    | 103  | 1          | 41           | 2       | 267
117 | 1        | 40         | 2     |   <null>    | 103  | 1          | 40           | 2       | 267
117 | 1        | 38         | 2     |   <null>    | 103  | 1          | 38           | 2       | 267

但是下面的查询不会返回任何行。注意最后的额外AND子句:

WITH src AS 
     (SELECT id AS s_id,
             moduleid AS s_moduleid, 
             instanceid AS s_instanceid, 
             tagid AS s_tagid, 
             componentid AS s_componentid 
      FROM component_junction WHERE id=103)
SELECT * FROM component_junction cj 
JOIN src ON s_moduleid=cj.moduleid 
         AND s_instanceid=cj.instanceid 
         AND s_tagid=cj.tagid 
WHERE cj.id=117 AND s_componentid != cj.componentid;

我知道值不同,因为我可以在第一个查询的结果集中看到它。 componentid的两个集合中都存在一些NULL值,因此我希望这些值不会显示在第二个查询中。

2 个答案:

答案 0 :(得分:4)

其中一个或两个值似乎为REPLACE。 Postgres支持ANSI标准NULL安全比较,因此请更改

NULL

为:

s_componentid != cj.componentid

答案 1 :(得分:0)

由于一个NULL值与另一个NULL值不同,您可以对ComponentID列使用ISNULL函数,如下所示:

 WITH src AS 
 (SELECT id AS s_id,
         moduleid AS s_moduleid, 
         instanceid AS s_instanceid, 
         tagid AS s_tagid, 
          ISNULL(componentid,'') AS s_componentid 
  FROM component_junction WHERE id=103)
  SELECT * FROM component_junction cj 
  JOIN src ON s_moduleid=cj.moduleid 
     AND s_instanceid=cj.instanceid 
     AND s_tagid=cj.tagid 
     WHERE cj.id=117 
     AND ISNULL(s_componentid,'') != ISNULL(cj.componentid,'');