Tuesday, October 11, 2011

Left Join Example - SQL Query

Today, I had to write a MySQL query that found entries in one table that had no corresponding entries in a second table. The schema was written in such a a way that table A's id column corresponded to an id column in  table B (call the column tableA_id.) It's possible that some entries in table A might not have corresponding entries in table B (and vice versa, but I didn't actual care about the unique table B entries.) Table A was constructed with an "id" column and a "name" column. Table B was created like so: "id" "attribute" and "tableA_id"

The query (a rather simple one, at that...)

select A.id, A.name from A left join B  on A.id = B.tableA_id where B.tableA_id is NULL