比较同一列的两列

时间:2013-03-03 22:30:19

标签: sql northwind

我想显示所有订单的订单ID 放置放置底部美元市场所有订单

我使用了fllowing查询

select 
    Orders.OrderID 
from 
    Orders 
where 
    Orders.OrderDate > (
        select 
            Orders.OrderDate 
        from 
            Orders 
        where 
            Orders.CustomerID = (
                select 
                    Customers.CustomerID 
                from 
                    Customers 
                where 
                    Customers.CompanyName='Bottom-Dollar Markets'
            ) 
        );

但它会错误子查询重新获得多个值

我使用的是northwind数据库

1 个答案:

答案 0 :(得分:5)

您的两个子查询都可以返回多行,这在您使用标量比较操作时是不允许的 - 在您的情况下分别为>=

请改为尝试:

select Orders.OrderID
from Orders
where Orders.OrderDate > (
  select max(Orders.OrderDate)
  from Orders
  where Orders.CustomerID in (
    select Customers.CustomerID
    from Customers
    where Customers.CompanyName='Bottom-Dollar Markets'
  )
);

您实际上并不需要比较所有订单,因为如果客户的订单大于Bottom-Dollar Markets放置的最新订单,则会跟随它也比早先的订单更大。

或者,这适用于JOIN

select Orders.OrderID
from Orders
where Orders.OrderDate > (
  select max(Orders.OrderDate)
  from Orders join Customers on Orders.CustomerID = Customers.CustomerID
  where Customers.CompanyName='Bottom-Dollar Markets'
);