简体   繁体   中英

How do I select only rows that don't have a corresponding foreign key in another table in MySQL?

I have 3 tables:

  • listing
  • photo
  • calendar

"photo" and "calendar" both have a "listing_id" column in them and every "listing" has a "photo". But I only want to select rows that have no entry in the "calendar" table with the matching "listing_id".

I'm not sure if I'm saying it correctly, but any help would be greatly appreciated. And if someone could show me CodeIgniter syntax, that'd be even better.

This will produce the list of calendar.free_date values that should not be returned because their associated listing_id values do not exist in the listing table.

select free_date from calendar c 
 where not exists (select * from listing 
                    where listing_id = c.listing_id);

Should work as an SQL query. Not sure about CI syntax. Sorry!

SELECT * FROM listing WHERE listing_id NOT IN (SELECT listing_id FROM calendar)

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