简体   繁体   中英

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

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.

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

Left join brings all the t1 records, then filter out those that have t2.galleryid NULL (no records in t2)

SELECT id, galleryname
FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2 ON t1.id = t2.galleryid
WHERE t2.galleryid IS NULL
SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.galleryid
WHERE table2.galleryid IS NULL

Someone posted an answer (then deleted it) that gave me ONLY the record that was in both. All others here seemed to give errors but using that original post I made one change and it worked.

Original:

SELECT * FROM table1 INNER JOIN table2 ON galleries.id = images.galleryid

(this gave me just the one that was in both)

Adding the !:

SELECT * FROM table1 INNER JOIN table2 ON galleries.id != images.galleryid

(this gave me what I needed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM