如何处理 SQL IN 运算符在只需要一个值时返回多个值?

How to deal with SQL IN Operator returning multiple values when only one is needed?

我正在处理看起来像这样的多父子层次结构。这是具有 105k 条记录的 table 的子集。

NodeKey ParentKey Child Parent
1 A
2 B
3 C A
4 D B
5 D C

我需要使用具有以下条件的数据填充列 ParentKey。

如果Parent中的值为NULL,则ParentKey中的值也设置为NULL

如果Parent里的值是NOT NULL,Child里也有,那么select对应的NodeKey,设置为ParentKey里的值(见第2条table)。

我可以这样做,但是当父列中的值在子列中出现不止一次时出现问题。

在第 5 行中,在 3 或 4 之间选择哪个值并不重要。它可以是任何一个。

NodeKey ParentKey Child Parent
1 A
2 B
3 1 C A
4 2 C B
5 Doesn't matter if 3 or 4 D C
SELECT (CASE WHEN Parent IS NULL THEN NULL 

ELSE 

(SELECT NodeKey from table WHERE Parent IN (SELECT Child from table)) END) as ParentKey

执行此代码时,它告诉我“子查询返回的值多于 1”,这是有道理的。但无论我把 max()min() 放在哪里,它都不起作用。

当我把max() 在 NodeKey 前面它只是 returns 一个充满 NULL 和 105314 的列。105314 是 table.

中的行数

我正在使用 SQL Server Management Studio 17。

如果不管用什么ParentKey,可以用MIN(MAX)函数:

SELECT 
    TBL.NodeKey,
    PK AS ParentKey,
    TBL.Child, 
    TBL.Parent
FROM TBL
LEFT JOIN (
    SELECT Child, MIN(NodeKey) PK FROM TBL GROUP BY Child
) P ON P.Child = TBL.Parent;

Test MS SQL query

或其他版本:

SELECT 
    TBL.NodeKey,
    MIN(P.NodeKey) AS ParentKey,
    TBL.Child, 
    TBL.Parent
FROM TBL
LEFT JOIN TBL P ON P.Child = TBL.Parent
GROUP BY TBL.NodeKey, TBL.Child, TBL.Parent;

结果:

+=========+===========+=======+========+
| NodeKey | ParentKey | Child | Parent |
+=========+===========+=======+========+
| 1       | (null)    | A     | (null) |
+---------+-----------+-------+--------+
| 2       | (null)    | B     | (null) |
+---------+-----------+-------+--------+
| 3       | 1         | C     | A      |
+---------+-----------+-------+--------+
| 4       | 2         | C     | B      |
+---------+-----------+-------+--------+
| 5       | 3         | D     | C      |
+---------+-----------+-------+--------+