Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

sql - join two different tables and remove duplicated entries

I'm complete novice in sql queries. I have two tables:

table1:

id_s  name   post_code     city     subject
------------------------------------------
1     name1  postal1    city1    subject1
2     name2  postal2    city2    subject2
3     name3  postal3    city3    subject3
4     name4  postal4    city4    subject4
...
~350

table2:

id_p  name   post_code     city     subject
------------------------------------------
1     name1  postal1    city1    subject1
2     name2  postal2    city2    subject2
3     name3  postal3    city3    subject3
4     name4  postal4    city4    subject4 
...
~1200

I want to join both tables, and remove entries with same name and postal code. I found some answers on how to do it but they were too complicated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use UNION clause, UNION will check for duplicates and only distinct rows will be returned

SELECT * FROM table1
UNION
SELECT * FROM Table2

Edit: To store data from both table without duplicates, do this

INSERT INTO TABLE1
SELECT * FROM TABLE2 A
WHERE NOT EXISTS (SELECT 1 FROM TABLE1 X 
                  WHERE A.NAME = X.NAME AND 
                  A.post_code = x.post_code)

This will insert rows from table2 that do not match name, postal code from table1

Alternative is that You can also create new table and not touch table1 and table2

CREATE TABLE TABLENAME AS
SELECT * FROM table1
UNION
SELECT * FROM Table2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...