我有3张桌子:
> CP_carthead(idOrder)
> CP_cartrows(idOrder,idCartRow)
> CP_shipping(idCartRow,idShipping,dateShipped)
每个idOrder可以有多个idCartRows.
我想得到CP_shipping中存在所有idCartRows的所有订单.这似乎应该很简单,但我在网上找不到太多东西.
这是我的查询:
SELECT
s.idOrder
, s.LatestDateShipped
FROM
CP_carthead o
LEFT OUTER JOIN (
SELECT
MAX(s.dateShipped) [LatestDateShipped]
, r.idOrder
FROM
CP_shipping s
LEFT OUTER JOIN CP_cartrows r ON s.idCartRow = r.idCartRow
GROUP BY
r.idOrder
) s ON o.idOrder = s.idOrder
最佳答案 您的查询是从“s”而不是订单返回行.根据您的问题,我提出了这个问题:
select o.*
from CP_Carthead o
where o.orderId in (select cr.idOrder
from cp_cartrows cr left outer join
cp_shipping s
on cr.idCartRow = s.IdCartrow
group by cr.idOrder
having count(s.idCartRow) = COUNT(*)
)
in语句中的子查询是获取其所有纸箱都在发货的订单.