MYSQL insert after sub query with count

落爺英雄遲暮 提交于 2019-12-12 11:34:31

问题


I'm trying to INSERT some data into a table but only when the subquery COUNT is > 0.

This is what I have so far.

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


回答1:


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;

Another way would be:

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



回答2:


Try this::

INSERT INTO users_friends (userId, friendId) 
(SELECT 77, 100  FROM users GROUP BY email HAVING email= 'a@g.com' and count(id)>0)



回答3:


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


来源:https://stackoverflow.com/questions/14833940/mysql-insert-after-sub-query-with-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!