问题描述:

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 = '[email protected]') > 0

Both queries work independently FYI.

This should be a simple fix hopefully. Cheers

网友答案:

SQLFiddle demo if there are records '[email protected]'

SQLFiddle demo if there are NOT records '[email protected]'

INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 
FROM users WHERE email = '[email protected]' LIMIT 1;

Another way would be:

INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 
FROM dual
WHERE EXISTS
      ( SELECT * FROM users WHERE email = '[email protected]' ) ;
网友答案:

Try this::

INSERT INTO users_friends (userId, friendId) 
(SELECT 77, 100  FROM users GROUP BY email HAVING email= '[email protected]' and count(id)>0)
网友答案:
INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 FROM users WHERE email = '[email protected]'
GROUP BY email
HAVING COUNT(id) > 0
相关阅读:
Top