英文:
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 |
英文:
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 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论