我在删除两个不同列之间的重复项时遇到问题。这是我当前的选择查询:
SELECT e.id AS EventId,
rt.player_nbr AS PlayerId,
rt.partner_nbr AS PartnerId
FROM eventTable e
INNER JOIN resultsTable rt ON e.id = rt.id
结果如下:
EventId | PlayerId | PartnerId
1049 | 20652 | 80458
1049 | 20702 | 310816
1049 | 80394 | 190666
1049 | 80394 | null
1049 | 80458 | 20652
1049 | 190666 | 80394
从结果中,您可以看到PlayerId和PartnerId刚刚失败的重复项。我想将重复的行删除到这样的位置:
EventId | PlayerId | PartnerId
1049 | 20652 | 80458
1049 | 20702 | 310816
1049 | 80394 | 190666
1049 | 80394 | null
到目前为止,我已尝试过这个和其他一些事情但没有成功:
SELECT e.id AS EventId,
rt.player_nbr AS PlayerId,
rt.partner_nbr AS PartnerId
FROM eventTable e
INNER JOIN resultsTable rt ON e.id = rt.id
WHERE NOT EXISTS(
SELECT *
FROM eventTable e2
INNER JOIN resultsTable rt2 ON e2.id = rt2.id
WHERE rt2.player_nbr = rt.partner_nbr
AND rt2.partner_nbr = rt.player_nbr
)
有关我如何才能最好地处理此问题的任何建议?提前谢谢。
答案 0 :(得分:1)
您的示例查询使用not exists
,因此让我们沿着这条路继续前进。逻辑是你希望所有行都是player_nbr < partner_nbr
。然后,您需要player_nbr > partner_nbr
为真的行,但是有player_nbr < partner_nbr
的其他行。以下是SQL中的逻辑:
SELECT e.id AS EventId,
rt.player_nbr AS PlayerId,
rt.partner_nbr AS PartnerId
FROM eventTable e INNER JOIN
resultsTable rt
ON e.id = rt.id
WHERE rt.player_nbr < rt.partner_nbr OR
NOT EXISTS (SELECT 1
FROM resultsTable rt2
WHERE rt2.id = rt.id AND
rt2.player_nbr = rt.partner_nbr AND
rt2.partner_nbr = rt.player_nbr
);