开发者

Find records that do not have related records in SQL

开发者 https://www.devze.com 2022-12-19 02:37 出处:网络
I have 2 tables (Orders, Orde开发者_StackOverflow中文版rItems) that are related based on a column OrderID.I need to find all Orders that do not have any OrderItems.We use JOIN to find related data. To

I have 2 tables (Orders, Orde开发者_StackOverflow中文版rItems) that are related based on a column OrderID. I need to find all Orders that do not have any OrderItems.


We use JOIN to find related data. To find data without any related data, we can use an anti-join.

The following joins the tables, then selects those without any order items. This tends to be more efficient that a WHERE id NOT IN (...) style query.

select *
from
    Orders O
    left outer join OrderItems I
    on I.OrderId = O.Id
where
    I.Id is null


Select * From Orders Where OrderID not in (Select Distinct OrderID From OrderItems)


try with LEFT EXCEPTION JOIN

select *
from Orders
LEFT EXCEPTION JOIN OrderItems ON ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号