带有count的子查询后插入MYSQL

我正在尝试将一些数据插入到表中,但仅当子查询COUNT是> 0.

这就是我到目前为止所拥有的.

INSERT INTO users_friends (userId, friendId) VALUES (77, 100) 
WHERE 
(SELECT COUNT(id) FROM users WHERE email = 'a@g.com') > 0

两个查询都独立工作.

希望这应该是一个简单的修复.干杯

最佳答案
SQLFiddle demo if there are records ‘a@g.com’

SQLFiddle demo if there are NOT records ‘a@g.com’

INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 
FROM users WHERE email = 'a@g.com' LIMIT 1;

另一种方式是:

INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 
FROM dual
WHERE EXISTS
      ( SELECT * FROM users WHERE email = 'a@g.com' ) ;

转载注明原文:带有count的子查询后插入MYSQL - 代码日志