【问题标题】:get the opposite results from a SELECT query从 SELECT 查询中得到相反的结果
【发布时间】:2012-11-10 05:22:35
【问题描述】:

这些是我的桌子:

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

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

任何建议将不胜感激。

【问题讨论】:

    标签: mysql select join left-join


    【解决方案1】:

    我不确定为什么您的 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');
    

    【讨论】:

    • 效果很好。我没有使用别名,这是我的错误。非常感谢您的帮助!!!
    【解决方案2】:

    当然,您必须将您的 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 风格的连接。没有人再做旧式加入了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多