tags:

views:

125

answers:

2
SELECT username, (SELECT follow 
                  FROM follow 
                  WHERE follow_user_id = user_id) AS following
FROM user
WHERE user_id = 1

I want to know how I can check if follow (sub-query (select follow ...)) returns a value. If it did, then replace it with 'yes'. If it didn't, then replace it with 'no'.

+7  A: 

Use a case statement

select username, 
  Case When Exists 
      (select * from follow 
       where follow_user_id = user_id)
    Then 'Yes' Else 'No' End following
from user
where user_id = 1
Charles Bretana
This was faster than my solution in the test case I did, voted this one up.0.34 sec instead of 0.42 sec (for about one million rows in each table on my desktop).
Johan Soderberg
Yes, Exists stops reading data as soon as it finds a single row.... Count(*) has to.... well... count ALL the rows.
Charles Bretana
A: 

SELECT u.username, IF ((SELECT COUNT(*) FROM follow f WHERE f.follow_user_id = u.user_id),"yes","no") FROM user u WHERE u.user_id = 1

Johan Soderberg