these are my tables:
`room`(roomID,roomNum)
`customer`(customerID,Surname,etc)
`contract`(contractID,roomID,weekNum)
`paymen`t(paymentID,customerID,contractID,YearKoino)
and when i use the following query:
`select` room.roomnum
`from` payment,contract,room,customer
`where` payment.contractID = contract.contractID
`and` contract.roomID=room.roomID
`and` customer.customerID=payment.customerID
`and` contract.weeknum='40'
`and` payment.YearKoino='2007' ;
the results i am getting are:
+---------+
| roomnum |
+---------+
| Δ-12 |
| Γ-22 |
| Α-32 |
| Γ-21 |
| Δ-11 |
| Ε-12 |
| Γ-31 |
| Ε-22 |
| Α-22 |
| Δ-12 |
| Γ-12 |
+---------+
11 rows in set
what i want to do is to run a query that gives me the exact opposite results(roomnums in table room that are not in table payment).This can be done by comparing the roomum results from the above query with the column roomnum in the room table.some of my efforts so far :
`Select` room.roomnum
`from` room
`where` NOT EXISTS
(`select` room.roomnum
`from` payment,contract,room,customer
`where` payment.contractID = contract.contractID
`and` contract.roomID=room.roomID
`and` customer.customerID=payment.customerID
`and` contract.weeknum='40'
`AND` payment.YearKoino='2007');
Empty set
and
`SELECT` *
`FROM` customer a
`LEFT OUTER JOIN` payment b
`on` a.customerID=b.customerID
`where` a.customer is null;
i also tried to replace the "NOT EXISTS" with the "NOT IN" but in vain.I have read that the best way to do that is by using the "left join".well i can do it when i have to compare to simple tables.but in my example i have to compare a column with a column that is in a join of tables...
any advice would be appreciated.
I am not sure why your not in
didn't work.
This should work (using not in with table name aliases):
Select r1.roomnum
from room AS r1
where r1.roomnum NOT IN
(select r2.roomnum
from payment,contract,room as r2,customer
where payment.contractID = contract.contractID
and contract.roomID=r2.roomID
and customer.customerID=payment.customerID
and contract.weeknum='40'
AND payment.YearKoino='2007');
Of course you must correlate your NOT EXISTS query with your main query
Select
roomnum
from
room main
where
NOT EXISTS (
select 1
from payment
inner join contract on payment.contractID = contract.contractID
inner join room on contract.roomID = room.roomID
inner join customer on customer.customerID = payment.customerID
where contract.weeknum='40'
and payment.YearKoino='2007'
and room.roomnum = main.roomnum -- < correlation to main query
);
Also, learn SQL-92 style joins. Nobody does old style joins anymore.
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.