1

我有一个多对多表已经变得有点混乱,我正在寻找更新架构以防止将来发生这种情况。为此,我首先需要清理现有数据以用作合并脚本的源。不知道如何定义这种命中 Google 的查询并没有真正的帮助。

简单地分解一下,这就是我正在查看的内容以及我想要提取的内容。

DECLARE @TestTable
TABLE ([IdA] INT, [IdB] INT);

DECLARE @Expected
TABLE ([KeyId] INT, [MemberId] INT);

INSERT INTO @TestTable
VALUES
    (1, 2),
    (2, 1),
    (1, 3),
    (4, 1),
    (12, 4),

    (5, 6),
    (6, 7),

    (8, 9),

    (11, 10)

INSERT INTO @Expected
VALUES
    (1, 1),
    (1, 2),
    (1, 3),
    (1, 4),
    (1, 12),

    (5, 5),
    (5, 6),
    (5, 7),

    (8, 8),
    (8, 9),

    (10, 10),
    (10, 11)
  • 组的最低 ID 应被视为关键
  • 组的成员数将始终小于 20
  • 只要结果数据集正确,排序并不重要

非常感谢。

4

1 回答 1

4

这是实现您想要做的事情的一种方法:

这是一个SQLFiddle

--Let's copy the rows in as they are to begin with
INSERT INTO 
  @Expected
SELECT
   [IdA]
  ,[IdB]
FROM 
  @TestTable


--Lets switch the column values where the higher ID's are in column B  
UPDATE @Expected
SET [KeyId] = [MemberId], [MemberId] = [KeyId]  
WHERE [KeyId] > [MemberId]

--Now lets set the KEY IDs
UPDATE
  E
SET
  E.[KeyId] = E1.[KeyId]
FROM
  @Expected E
INNER JOIN
  @Expected E1 
ON
  E1.[MemberId] = E.[KeyId]

--and you wanted mappings for the keys to themselves in your result set, so let's add those
INSERT INTO
  @Expected
SELECT
  [KeyId]
 ,[KeyId]
FROM
  @Expected E 
WHERE NOT EXISTS
  (SELECT * FROM @Expected WHERE [KeyId] = E.[KeyId] AND [MemberId] = [KeyID])

SELECT DISTINCT 
  * 
FROM 
  @Expected

请注意,我最后选择了 DISTINCT,因为我没有从结果集中删除重复项。

于 2012-07-12T12:52:00.800 回答