I have two tables, one for users, and one for renewals. I want to select all users who have a row in the renewals table for a specific year, and I can do this fine. However, if there are more than one row for a specific user for the specific year in the renewals table, I get duplicates, which I don’t want.
I assume it’s because I still don’t quite understand JOINS, so here is my query:
SELECT * FROM `users` AS US
RIGHT JOIN `usermeta` UM1
ON UM1.`user_id` = US.`ID`
RIGHT JOIN `membership_renewals` MR
ON MR.`user` = US.`ID` AND MR.year = '2011'
WHERE
UM1.meta_key = 'member'
AND UM1.meta_value = 1
AND US.`user_pass` NOT LIKE '-%'
You can do it with JOINS, but I like to do this kind of thing with EXISTS and subqueries, because it reads more like the rule I am trying to enforce.
P.S. I really don’t like using RIGHT JOIN unless I have to. If you can, just user INNER JOIN. If not, rearrange the FROM so you can use LEFT JOIN. Again, it is just for readability, but I don’t know that i have ever used RIGHT JOIN.