(一个表)插入行

时间:2019-05-22 05:42:21

标签: sql postgresql sql-insert insert-select

这个问题是this one的继续。

我有下表egr

+---------+------------+
|  offid  |  groupid   |
+---------+------------+
|       1 | 101        |
|       1 | 202        |
|       2 | 202        |
|       2 | 404        |
+---------+------------+

我想插入offid 2所没有的缺少的groupid(与offid 1相比)。结果将是:

+---------+------------+
|  offid  |  groupid   |
+---------+------------+
|       1 | 101        |
|       1 | 202        |
|       2 | 202        |
|       2 | 404        |
|       2 | 101        |   --> new row to insert
+---------+------------+

我的尝试,基于我其他问题的答案(无效):

INSERT INTO egr (offid, groupid)
  SELECT 2, egr1.groupid
  FROM egr AS egr1 
  WHERE egr1.offid = 1
  AND NOT EXISTS
    (select 1
                  from egr e2
                  where e2.groupid = egr1.groupid and 
                        e2.offid in (1, 2) and
                        e2.offid <> egr1.offid 
                 );

1 个答案:

答案 0 :(得分:2)

使用except运算符可能更容易实现:

INSERT INTO egr (offid, groupid)
SELECT 2, groupid
FROM   egr
WHERE  offid = 1
EXCEPT
SELECT 2, groupid
FROM   egr
WHERE  offid = 2