这些是我的表格:
`room`(roomID,roomNum)
`customer`(customerID,Surname,etc)
`contract`(contractID,roomID,weekNum)
`paymen`t(paymentID,customerID,contractID,YearKoino)
当我使用以下查询时:
`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' ;
我得到的结果是:
+---------+
| roomnum |
+---------+
| Δ-12 |
| Γ-22 |
| Α-32 |
| Γ-21 |
| Δ-11 |
| Ε-12 |
| Γ-31 |
| Ε-22 |
| Α-22 |
| Δ-12 |
| Γ-12 |
+---------+
11 rows in set
我想做的是运行一个查询,给出完全相反的结果(表房间中的房间号不在表付款中)。这可以通过将上述查询的房间号结果与列 roomnum 进行比较来完成在房间的 table 上。到目前为止我的一些努力:
`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
和
`SELECT` *
`FROM` customer a
`LEFT OUTER JOIN` payment b
`on` a.customerID=b.customerID
`where` a.customer is null;
我还尝试用“NOT IN”替换“NOT EXISTS”,但徒劳无功。我读到最好的方法是使用“left join”。好吧,当我有与简单的表进行比较。但在我的示例中,我必须将一列与表连接中的一列进行比较...
如有任何建议,我们将不胜感激。
最佳答案
我不确定为什么您的 not in
不起作用。
这应该有效(不使用表名别名):
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');
关于mysql - 从 SELECT 查询中得到相反的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502068/