I’m trying to get a list of IDs from three tables.
table_one
---------
| id | other_data |
table_two
---------
| this_id | user_id | time_qual |
table_three
---------
| this_id | second_qual |
I want to get a list back of table_one ids with the following qualifications:
- the
idis also found intable_three‘sthis_id second_qualintable_threeis equal to 1this_idintable_twoequalstable_one‘sidAND in the same row,table_two‘suser_idequals the php variable$user_idANDtime_qualin that row equals 1.- but also include
ids that qualify for #1 and #2, and not #3 iftable_one‘sidand the php variable$user_idisn’t found on the same row oftable_two
This is my attempt:
SELECT tb1.id FROM table_one tb1
INNER JOIN table_two tb2
INNER JOIN table_three tb3
WHERE tb2.this_id = tb1.id
AND tb3.this_id = tb1.id
AND tb3.second_qual = 1
AND ((tb2.user_id = $user_id AND tb2.time_qual = 1)
OR ($user_id NOT IN (SELECT user_id FROM table_two)))
GROUP BY tb1.id
I’m guessing there should be a UNION in there and that tb2.this_id = tb1.id eliminates the results I want from #4, but I’m not sure what to do.
Thanks in advance!
To the best of my ability to parse your requirements, I think this is the answer. Let me know if it misses and I can amend: