WHERE NOT EXISTS 在尝试根据另一个 table 的条件独立插入时不起作用

WHERE NOT EXISTS not working when trying to insert based independent on condition from another table

我正在尝试根据另一个 table 的条件将值插入 table。不是基于忽略重复值。但我不断收到语法错误。不确定如何进行。

我想要实现的是只允许将用户添加到组中,前提是在独立 table 中该用户未阻止当前用户:

INSERT INTO users_to_groups(user_id, group_id) 
VALUES (1,'A') 
WHERE NOT EXISTS (SELECT * FROM users_to_users WHERE user_id_a=2 AND user_id_b=1 AND user_blocked=1);

编辑

我想一次插入多行

你可以这样做:

INSERT INTO users_to_groups(user_id, group_id) 
    SELECT x.user_id, x.group_id
    FROM (SELECT 1 as user_id, 'A' as group_id) x
    WHERE NOT EXISTS (SELECT 1
                      FROM users_to_users utu
                      WHERE utu.user_id_a = 2 AND
                            utu.user_id_b = 1 AND
                            utu.user_blocked = 1
                     );

如果你想INSERT只有一行你可以尝试如下:

INSERT INTO users_to_groups(user_id, group_id) 
SELECT 1,'A'
FROM dual
WHERE NOT EXISTS
    (SELECT * FROM users_to_users
     WHERE user_id_a=2 AND user_id_b=1 AND 
     user_blocked=1);

如果你想要INSERT一个真实的查询结果,你可以用你的逻辑

改变SELECT语句

例如:

INSERT INTO users_to_groups(user_id, group_id) 
SELECT u.id,'A'
FROM users u
WHERE NOT EXISTS
    (SELECT * FROM users_to_users
     WHERE user_id_a=u.id AND user_id_b=1 AND 
     user_blocked=1);

但是你不能在 WHERE 条件下使用 INSERT INTO ... VALUES 因为你有语法错误