I wonder why these statements are not the same (the first one worked for me)
AND user_thread_map.user_id = $user_id
AND user_thread_map.thread_id = threads.id
AND user_thread_map.user_id = users.id
AND user_thread_map.thread_id = threads.id
AND users.id = $user_id
Shouldn’t they be the same? In the 2nd one I linked all the tables in the first 2 lines, then I tell it to select where users.id = $user_id.
Can someone explain why the 2nd statement doesn’t work? Because I thought it would.
Assuming you’re getting no rows returned (you don’t really say what the problem is, so I’m guessing a bit here), my first thought is that there are no rows in
userswhereidis equal to$user_id.That’s the basic difference between those two SQL segments, the second is a cross-join of the
user_thread_map,threadsanduserstables. The first does not join withusersat all, so that’s where I’d be looking for the problem.It appears that your
user_thread_maptable is a many-to-many relationship betweenusersandthreads. If that is true, are you sure you have a foreign key constraint between the ID fields in that table to both corresponding other tables, something like:If you have those foreign key constraints, it should be impossible to end up with a
user_thread_map(user_id)value that doesn’t have a correspondingusers(id)value.If those constraints aren’t there, a query can tell you which values need to be fixed before immediately adding the constraints (this is important to prevent the problem from re-occurring), something like: