如何正确执行具有特定要求的子查询

时间:2019-02-06 17:05:47

标签: mysql

使用指定的信息here

对于在新加坡购买的商品,我需要显示货件的ShipperName,ShipmentID和DepartureDate。我还需要使用子查询来执行此操作。结果需要按托运人名称升序排序,然后按降序按DepartureDate排序。

我是mysql的新手,子查询和联接有点难理解。到目前为止,我只是想澄清一下,因为我尝试失败。

SELECT city FROM item WHERE = city LIKE 'Singapore' and ( 
SELECT ShipperName, ShipmentID, DepartureDate FROM shipment);

1 个答案:

答案 0 :(得分:0)

您可以通过联接三个表来实现

select ShipperName, ShipmentId, DepartureDate
from shipment s
inner join shipment_item si on si.shipmentId = s.shipmentId
inner join item i on i.ItemID = s.ItemID and City = 'Singapure' 
Order by ShipperName Asc, DepartureDate Desc

似乎您不需要子查询。但是您也可以这样做

select ShipperName, ShipmentId, DepartureDate
from shipment s
where exists (
   select 1 from shipment_item si 
   inner join item i on i.ItemID = s.ItemID 
   where si.shipmentId = s.shipmentId and City = 'Singapure' 
)

按ShipperName Asc,DepartureDate Desc排序