简体   繁体   中英

Select column from one table, where it is NULL in another

I'm trying to list data from a table, where the equivalent data in another table has not been entered. A bit wordy to explain but exactly what I'm trying to do is the following:

I'm really stumped trying to pull data where it doesn't exist in room, any help is appreciated.

Thank you!

e:

SELECT
    COUNT(a.x) AS p,
    COUNT(a.x) AS q,
FROM 
    x
LEFT JOIN b ON a.x= b.x
WHERE b.xis NULL;
select h.*
from hotel as h
left join room as r
on h.number = r.hotelnumber
where r.hotelnumber is null

Although Santhosh posted a good solution, I would like to advertise EXISITS, since it is more idiomatic. The query should read to a new developer like a sentence which describes what you want to do (if possible).

And the oracle optimizer seems to work really good with EXISTS in big queries ( I can't cite exact sources, just from many queries on asktom or similar sites, EXISTS seems to optimize in many situations where similar statements might fail inside a big query... )

SELECT * FROM hotel h
WHERE NOT EXISTS
( SELECT * FROM room r
  WHERE r.hotelnumber = h.number
)

Read: Give me all Hotels, where there is no Room having its hotel number. --> Give me all hotels without any rooms.

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