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
194 views
in Technique[技术] by (71.8m points)

MYSQL - how to merge this 2 tables to get a specific table output

I have been struggling and would like some ideas/thoughts on how to do this. Unfortunately, I inherited these tables from a former coworker and need to work with what I got. I want to some how merge Table A with Table B to get Table C.

Table A:

ID ID_P IP_Type Name
1 Cat Animal Henry
2 Cat Apple
3 Cat Bananas
4 Shark Animal George
5 Cat Animal Richard
question from:https://stackoverflow.com/questions/65895048/mysql-how-to-merge-this-2-tables-to-get-a-specific-table-output

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

1 Reply

0 votes
by (71.8m points)

You will need a UNION between the full contents of table A and you can use a LEFT JOIN between A and B to look for non-existing records based on ID_P Name for the other half of the UNION.

Use literal NULLs to fill the columns that do not exist in the B side of the union, to produce the same column set.

-- Take all the cols from table A
SELECT
  ID,
  ID_P,
  IP_Type,
  Name
FROM tableA
-- Combine with a filtered set from B
UNION
SELECT
  NULL AS ID,
  b.ID_P,
  NULL AS ID_Type,
  b.name
FROM
  tableB b
  -- Join on ID_P and Name
  LEFT JOIN tableA a ON b.ID_P = a.ID_P AND b.Name = A.Name
-- NULLs on the left join mean non-matching
WHERE a.ID_P IS NULL

Here it is in action


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

...