SELECT 来自 Child Table 的记录不在另一个 Parent 没有其他 Children

SELECT Records From Child Table That Are Not In Another And Parent Has No Other Children

我正在尝试向 select child table 中的所有孤立记录编写查询,但仅当孤立记录是 [=] 中唯一的项目时31=].

我有两个来自不同系统的独立数据库,因此我无法使用外键强制执行参照完整性约束。每个的简单架构如下:

ITEMS
Order  |  Item
----------------
1      |   A1
1      |   A2
2      |   A1

COMP
Item
-------
A2

以上述数据为例,我想要查询 returns 订单 2,因为 parent 上唯一可用的商品已被删除。

到目前为止,我有以下查询 returns 我所有孤立的记录,包括订单 1。

SELECT Order FROM Items as i LEFT JOIN Comp as c ON i.Item = c.Item WHERE c.Item IS NULL

有什么想法吗?

当我创建两个表并输入数据时,这里是查询和结果

CREATE TABLE Items(
  [Order] int,
  Item varchar(50)
);

CREATE TABLE Comp(
  Item varchar(50)
);

INSERT Items ([Order],Item)
VALUES (1, 'A1');
INSERT Items ([Order],Item)
VALUES (1, 'A2');
INSERT Items ([Order],Item)
VALUES (2, 'A1');

INSERT Comp (Item)
VALUES('A2');




SELECT i.[Order], i.Item 
FROM Items as i 
LEFT JOIN Comp as c ON i.Item = c.Item 
WHERE c.Item IS NULL

Order   Item
1       A1
2       A1

如果您 group by [Order] table ITEMS 在条件 having count(distinct [Item]) = 1 下,您将获得所有只有 1 件商品的订单。
然后使用 NOT EXISTS 检查 COMP 中是否存在这些订单中的任何一个,或者像您的查询一样使用左连接:

select i.[Order] from ITEMS i
where i.[Order] IN (
  select [Order] from ITEMS
  group by [Order]
  having count(distinct [Item]) = 1
)
and not exists (select 1 from COMP where [Item] = i.[Item])

或者:

select i.[Order] 
from ITEMS i left join COMP c
on c.[Item] = i.[Item]
where i.[Order] IN (
  select [Order] from ITEMS
  group by [Order]
  having count(distinct [Item]) = 1
)
and c.[Item] is null

参见demo

您的查询即将完成:

SELECT i.Order 
FROM 
  Items as i 
  LEFT JOIN Comp as c 
  ON i.Item = c.Item 
GROUP BY i.Order
HAVING COUNT(c.Item) = 0

此查询查找所有与订单相关的 c.Item 为空的订单

加入你的数据后看起来像:

i.Order | i.Item | c.Item
1       |   A1   |  null
1       |   A2   |  A2
2       |   A1   |  null

分组和计数c.Item给出;

i.Order | i.Item | COUNT(c.Item)
1       |   A1   |  1
2       |   A1   |  0

因为 count 向上计数,null 步长为 0,任何非 null 步长为 1

我们想要 i.Order=2 行,这是 HAVING 给我们的; HAVING 是在分组完成后应用的 where 子句。 (WHERE 子句在分组之前应用,不能用于此)

因此此查询会找到所有 c.Item 都为 NULL

的订单