简体   繁体   中英

SQL Join only if all records have a match

I have 3 tables:

  • CP_carthead (idOrder)
  • CP_cartrows (idOrder, idCartRow)
  • CP_shipping (idCartRow, idShipping, dateShipped)

There can be multiple idCartRows per idOrder.

I want to get all orders where 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM