从SELECT查询中获得相反的结果

时间:2012-11-21 21:05:47

标签: mysql select join left-join

这些是我的表格:

`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  

我想要做的是运行一个查询,它给出了完全相反的结果(表空间中的roomnums不在表格支付中)。这可以通过比较上述查询的roomum结果与列roomnum来完成在房间里。到目前为止我的一些努力:

`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”但是徒劳无功。我读过这样做的最好方法是使用“左连接”。我可以做到这一点,当我有比较简单的表。但在我的例子中,我必须比较一个列与表连接中的列...

任何建议都将受到赞赏。

2 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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样式连接。没有人再做旧式的加入了。