(One table) insert rows

99封情书 提交于 2019-12-02 05:12:27

问题


This question is the continuation of this one.

I have the following table egr:

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

I would like to insert missing groupids that the offid 2 does not have (compared to offid 1). Result would be:

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

My try, based on the answer of my other question (not working):

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:


This may be easier to achieve using the except operator:

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


来源:https://stackoverflow.com/questions/56250022/one-table-insert-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!