Select Data from Left Join that doesn't exist in b
Login or Register to Bookmark this snippet
Selects data from two tables, that are left joined so matching data doesn't have to exist in the 2nd table for the data of the 1st to be returned.
Normally when selecting data from two tables with a "table1.field=table2.field" means that both tables must have a valid record for the row to be returned.
This particular query selects records from table1 that don't have a matching record in table2.
SELECT
COUNT(b.id) AS cnt,
a.*
FROM
table1 a
LEFT JOIN
table2 b
ON
b.id=a.id
GROUP BY
a.id
HAVING
cnt=0
Added by JC on 14th November, 2007
-
25th January, 2008 7:45 am Joel Pearson
-
Using a GROUP BY in this instance isn't the best idea, because you are relying on the fact that MySQL allows you to select other columns that aren't using Group By (Aggregate) Functions.
I know Postgres doesn't allow this either does Microsoft SQL Server.
Also using a GROUP BY would be a more expensive operation anyway.
You'd be better off just to check if b.id IS NULL in the WHERE clause. Eg
SELECT
a.*
FROM
table1 a
LEFT JOIN
table2 b
ON
b.id=a.id
WHERE b.id IS NULL
You must be registered and logged in to post a comment.
Login here to post a comment