[英]SQL Join only if all records have a match
I have 3 tables: 我有3张桌子:
There can be multiple idCartRows per idOrder. 每个idOrder可以有多个idCartRows。
I want to get all orders where all its idCartRows exist in CP_shipping.
我想它全部的 idCartRows在CP_shipping存在的所有订单。 This seems like it should be simple, but I haven't found much on the web.
这似乎很简单,但是我在网上找不到很多。
Here's my query now: 现在是我的查询:
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
Your query is returning rows from "s" and not the orders. 您的查询返回的是“ s”而不是订单中的行。 Based on your question, I came up with this query:
根据您的问题,我提出了以下查询:
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(*)
)
The subquery in the in
statement is getting orders all of whose cartrows are in shipping. in
语句中的子查询正在获取所有订单都在运输中的订单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.