4

我正在尝试将一些数据插入到表中,但仅当子查询 COUNT 大于 0 时。

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

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

两个查询都独立工作,仅供参考。

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

4

3 回答 3

5

SQLFiddle 演示,如果有记录 'a@g.com'

SQLFiddle 演示,如果没有记录 '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' ) ;
于 2013-02-12T13:47:29.277 回答
2

试试这个::

INSERT INTO users_friends (userId, friendId) 
(SELECT 77, 100  FROM users GROUP BY email HAVING email= 'a@g.com' and count(id)>0)
于 2013-02-12T13:48:18.717 回答
0
INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 FROM users WHERE email = 'a@g.com'
GROUP BY email
HAVING COUNT(id) > 0
于 2013-02-12T13:56:51.127 回答