I have a mysql query that works, but it's using a subquery. I'd like to write it using only joins. I have three tables:
risks
rid description
1 red
2 blue
3 yellow
4 green
5 black
details
did rid detail
1 1 reddish
2 1 blueish
3 2 reddish
4 3 greenish
5 4 grey
clearance
cid rid user clearance
1 1 23 1
2 2 25 2
3 2 27 0
4 2 29 2
5 3 25 1
and a value...
user = 25
I would like to show all 'rid' in the 'risks' table where 'detail' = 'reddish' but NOT show ANY rid where user = 25. For instance, with the data given above, if a user is 25, I never want rid = 2 or 5 to show up, only rid 1.
This query works with a subquery:
SELECT r.*, d.* FROM risks r LEFT JOIN details d on d.rid = r.rid
WHERE d.detail = 'reddish'
AND r.rid NOT IN (SELECT rid FROM clearance WHERE user = 25)
GROUP BY r.rid
When I run this query with my full set of data (30,000 rows in clearance and 1,000 rows in risks) the query takes from 80 to 120 seconds. When I remove the subquery, it takes .02 seconds or less.
Any ideas?
Thanks!
Jim