In my mysql database, I have two tables lists and shares. The lists table has all of the to do lists that users have created:
The shares table stores all lists that have been shared from one user to another:
What I want to do is get all lists for a user, both the ones they've created as well as the shared ones they have access to. Currently, I have a select statement that works perfectly when there is an entry in the shares table (doesn't matter if it relates to the specific user I'm retrieving results for).
As soon as I remove the result from the shares table and try to use that same multi-table SELECT statement, I get no results and I can't figure out why.
Here's the SELECT statement that I'm using:
SELECT DISTINCT `lists`.* FROM `lists`,`shares` WHERE `lists`.user_id = '$userid' OR (`shares`.sharedwith_id = '$userid' AND `lists`.id = `shares`.list_id) ORDER BY `lists`.datecreated DESC
You really should be using
JOIN instead of
SELECT DISTINCT `lists`.* FROM `lists` LEFT JOIN `shares` ON `lists`.`id`=`shares`.list_id AND `lists`.`user_id`=`shares`.`sharedwith_id` WHERE `lists`.`id` = ?
Finally, avoid SQL injection attacks: never embed arguments in your SQL. Pass your arguments as parameters.