Question

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

Was it helpful?

Solution

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' ) ;

OTHER TIPS

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)
INSERT INTO users_friends (userId, friendId) 
SELECT 77, 100 FROM users WHERE email = 'a@g.com'
GROUP BY email
HAVING COUNT(id) > 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top