Forum Moderators: open

Message Too Old, No Replies

[MySQL] Use where clause if number of rows in a table is bigger then 0

         

Bricius

7:52 pm on Aug 6, 2009 (gmt 0)

10+ Year Member



I need to have something similar:
SELECT * FROM users AS u LEFT JOIN user_ratings AS ur ON ur.user_id = u.id IF(COUNT(ur.id) > 0) THEN WHERE ur.rating_id=1;

If there are rows for that user in a user_ratings table, then select user in case his rating is 1. If there are no rows for that user, then select user without any exceptions.

Is it possible?

LifeinAsia

7:25 pm on Aug 7, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Welcome [webmasterworld.com] Bricius!

The following may work for you:
SELECT *
FROM users u LEFT OUTER JOIN user_ratings ur ON ur.user_id = u.id
WHERE ur.rating=1 OR ur.rating IS NULL

If a user can have multiple entries in the user_ratings table, then you'll need to use some more logic to filter out duplicates.

Bricius

12:09 pm on Aug 8, 2009 (gmt 0)

10+ Year Member



Bingo! That's exactly what I needed. Thanks :)

LifeinAsia

7:32 pm on Aug 8, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Glad it worked out for you.

If you are not familiar with OUTER JOINs, definitely look into them. They created a whole new wealth of possibilities (and alleviated many headaches) once I discovered them. :)