Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select fields in one table that are not in another table

Tags:

mysql

I have 2 tables in a MySQL DB:

Table 1 : id, galleryname
Table 2 : galleryid, <many other fields...>

Using PHP, I need to select all rows in Table 1 based on its ID where that id (galleryid) does not appear in Table 2.

Example: Table 1

1, flowers
2, water
3, mountains
4, winter

Table 2

3, ...

would return these rows from Table 1

1, flowers
2, water
4, winter

I'm not exactly sure how to go about this. I am pretty good at the basics of MySQL but I suspect this is a JOIN or a UNION that is out of my league.

Any help is appreciated.

like image 252
Chris Cummings Avatar asked Nov 16 '11 14:11

Chris Cummings


1 Answers

Try this:

SELECT * FROM table1
WHERE id NOT IN
    (SELECT galleryid FROM table2)

or

SELECT * FROM table1
LEFT JOIN table2
    ON table1.id = table2.galleryid
WHERE table2.galleryid IS NULL
like image 156
Marco Avatar answered Sep 23 '22 08:09

Marco