MYSQL 在子查询后插入计数
我正在尝试将一些数据插入到表中,但仅当子查询 COUNT 大于 0 时.
I'm trying to INSERT some data into a table but only when the subquery COUNT is > 0.
这是我目前所拥有的.
INSERT INTO users_friends (userId, friendId) VALUES (77, 100)
WHERE
(SELECT COUNT(id) FROM users WHERE email = 'a@g.com') > 0
这两个查询独立工作,仅供参考.
Both queries work independently FYI.
希望这应该是一个简单的修复.干杯
This should be a simple fix hopefully. Cheers
推荐答案
SQLFiddle 演示如果有记录'a@g.com'
SQLFiddle 演示,如果没有记录 'a@g.com'p>
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' ) ;
相关文章