2

这些是我的桌子:

`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  

我想要做的是运行一个查询,它给我完全相反的结果(桌子房间里的房间号码不在桌子付款中)。这可以通过将上述查询的房间结果与房间中的房间号码列进行比较来完成表。到目前为止我的一些努力:

`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;

我也尝试用“不存在”替换“不存在”,但徒劳无功。我已经读过最好的方法是使用“左连接”。当我必须比较时我可以做到简单的表。但在我的示例中,我必须将列与表连接中的列进行比较...

任何意见,将不胜感激。

4

2 回答 2

3

我不知道为什么你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');
于 2012-11-21T21:10:08.840 回答
1

当然,您必须您的 NOT EXISTS 查询与您的主查询相关联

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
);

另外,学习 SQL-92 风格的连接。没有人再做旧式加入了。

于 2012-11-21T21:11:47.233 回答