插入选定值

INSERT with selected value

来自Table:

user   | groupId
-------------------------
A      | 1
B      | 1
B      | 2
C      | 1
C      | 3         

我想找到所有没有 groupId = 2 的记录,然后插入它,就像这样:

INSERT INTO Table (user, groupId) VALUES (SELECT user FROM Table WHERE groupId != '2' GROUP BY user, '2')

结果应该是这样的:

user   | groupId
-------------------------
A      | 1
A      | 2
B      | 1
B      | 2
C      | 1
C      | 2
C      | 3
         

由于记录太多,无法一一查询或分开多个查询。有人可以帮我完成吗?谢谢!

使用insert . . . select:

INSERT INTO Table (user, groupId) 
    SELECT user, 2
    FROM Table 
    GROUP BY user
    HAVING SUM(CASE WHEN groupId = 2 THEN 1 ELSE 0 END) = 0;