合并两个表格并使用连接操作去除重复项。

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

Merge two tables and remove duplicates using join

问题

我尝试将两个表连接起来,但出现了重复的条目。以下是我的查询。

table1

col_id col_name
1 1234
2 2345
2 2654
3 4654
3 4054

table2

col_id col_status
1 1
2 2
3 1

我希望的结果如下:

col_id col_status col_name
1 1 1234
2 2 2345
3 1 4654

我尝试使用distinct和join,但是仍然出现了重复。

英文:

I am trying to join two tables but I am getting duplicate entries. below is my query.

table1

col_id col_name
1 1234
2 2345
2 2654
3 4654
3 4054

table2

col_id col_status
1 1
2 2
3 1

I am looking for result like

col_id col_status col_name
1 1 1234
2 2 2345
3 1 4654

I tried with distinct and join but I am getting duplicate.

答案1

得分: 0

你可以使用 GROUP BY 子句结合聚合函数 MAX() 来从查询中去除重复项。
例如:

SELECT table1.col_id, table2.col_status, MAX(table1.col_name) AS col_name
FROM table1
JOIN table2 ON table1.col_id = table2.col_id
GROUP BY table1.col_id, table2.col_status;
英文:

You can use the GROUP BY clause along with the aggregate function MAX() to remove the duplicates from your query.
For example:

SELECT table1.col_id, table2.col_status, MAX(table1.col_name) AS col_name
FROM table1
JOIN table2 ON table1.col_id = table2.col_id
GROUP BY table1.col_id, table2.col_status;

huangapple
  • 本文由 发表于 2023年3月8日 16:45:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670932.html
匿名

发表评论

匿名网友

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

确定