This query displays the correct result but when doing an EXPLAIN, it lists it as a “Dependant SubQuery” which I’m led to believe is bad?
SELECT Competition.CompetitionID, Competition.CompetitionName, Competition.CompetitionStartDate
FROM Competition
WHERE CompetitionID NOT
IN (
SELECT CompetitionID
FROM PicksPoints
WHERE UserID =1
)
I tried changing the query to this:
SELECT Competition.CompetitionID, Competition.CompetitionName, Competition.CompetitionStartDate
FROM Competition
LEFT JOIN PicksPoints ON Competition.CompetitionID = PicksPoints.CompetitionID
WHERE UserID =1
and PicksPoints.PicksPointsID is null
but it displays 0 rows. What is wrong with the above compared to the first query that actually does work?
The seconds query cannot produce rows: it claims:
But to clarify, I rewrite as follows:
So, on one hand, you are asking for rows on
PicksPointswhereUserId = 1, but then again you expect the row to not exist in the first place. Can you see the fail?External joins are so tricky at that! Usually you filter using columns from the “outer” table, for example
Competition. But you do not wish to do so; you wish to filter on the left-joined table. Try and rewrite as follows:For more on this, read this nice post.
But, as an additional note, performance-wise you’re in some trouble, using either subquery or the left join.
With subquery you’re in trouble because up to 5.6 (where some good work has been done), MySQL is very bad with optimizing inner queries, and your subquery is expected to execute multiple times.
With the
LEFT JOINyou are in trouble since aLEFT JOINdictates the order of join from left to right. Yet your filtering is on the right table, which means you will not be able to use an index for filtering theUSerID = 1condition (or you would, and lose the index for the join).