如何避免在一个列的值将进入第一张表的情况下出现重复的行?

huangapple go评论63阅读模式
英文:

How to avoid duplicate row where one column value will get first table?

问题

以下是翻译好的内容:

期望的结果:

id value name pid
1 55 a 27
2 56 b 23
3 57 c 22
5 58 d 23
6 59 e 22

这里:

id value name pid
1 55 a 29

该行将被移除。

英文:

I have two tables. And I want to avoid duplicate values where one column value will get from any table.
table a

id value name pid
1 55 a 27
2 56 b 23
3 57 c 22

table b

id value name pid
1 55 a 29
5 58 d 23
6 59 e 22

expected result

id value name pid
1 55 a 27
2 56 b 23
3 57 c 22
5 58 d 23
6 59 e 22

here

id value name pid
1 55 a 29

the row will be removed.

答案1

得分: 2

使用 UNION ALL 将两个表连接起来,并增加一个额外的优先级列,然后使用 ROW_NUMBER 分析函数来找到具有最高优先级的每一行:

SELECT id,
       value,
       name,
       pid
FROM   (
  SELECT id,
         value,
         name,
         pid,
         ROW_NUMBER() OVER (PARTITION BY id, value, name ORDER BY priority) AS rn
  FROM   (
    SELECT id, value, name, pid, 1 AS priority FROM a UNION ALL
    SELECT id, value, name, pid, 2 AS priority FROM b
  )
)
WHERE  rn = 1;

对于示例数据:

CREATE TABLE a (id, name, value, pid) AS
SELECT 1, 'a', 55, 27 FROM DUAL UNION ALL
SELECT 2, 'b', 56, 23 FROM DUAL UNION ALL
SELECT 3, 'c', 57, 22 FROM DUAL;

CREATE TABLE b (id, name, value, pid) AS
SELECT 1, 'a', 55, 29 FROM DUAL UNION ALL
SELECT 5, 'd', 58, 23 FROM DUAL UNION ALL
SELECT 6, 'e', 59, 22 FROM DUAL;

输出结果为:

ID VALUE NAME PID
1 55 a 27
2 56 b 23
3 57 c 22
5 58 d 23
6 59 e 22

fiddle

英文:

Use UNION ALL to concatenate the two tables with an additional priority column and then use the ROW_NUMBER analytic function to find each row with the highest priority:

SELECT id,
       value,
       name,
       pid
FROM   (
  SELECT id,
         value,
         name,
         pid,
         ROW_NUMBER() OVER (PARTITION BY id, value, name ORDER BY priority) AS rn
  FROM   (
    SELECT id, value, name, pid, 1 AS priority FROM a UNION ALL
    SELECT id, value, name, pid, 2 AS priority FROM b
  )
)
WHERE  rn = 1;

Which, for the sample data:

CREATE TABLE a (id, name, value, pid) AS
SELECT 1, 'a', 55, 27 FROM DUAL UNION ALL
SELECT 2, 'b', 56, 23 FROM DUAL UNION ALL
SELECT 3, 'c', 57, 22 FROM DUAL;

CREATE TABLE b (id, name, value, pid) AS
SELECT 1, 'a', 55, 29 FROM DUAL UNION ALL
SELECT 5, 'd', 58, 23 FROM DUAL UNION ALL
SELECT 6, 'e', 59, 22 FROM DUAL;

Outputs:

ID VALUE NAME PID
1 55 a 27
2 56 b 23
3 57 c 22
5 58 d 23
6 59 e 22

fiddle

huangapple
  • 本文由 发表于 2023年2月6日 03:21:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定