简体   繁体   中英

SQL Merge tables with two different columns

I have two tables that look like this:

table1:

在此处输入图片说明

table2:

在此处输入图片说明

and I'd like to merge them, to create a table with a header like this:

variablenname | mean | stddev | ms_form | dependent | fvalue | probf

The first nine rows should be the first table with empty values in the last 3 columns followed by the three rows from the second table with empty values in the first 4 columns. I'm sorry I can't post pictures or a third link, but my reputation is too low. I hope it's understandable.

I tried to create a new table and select everything from both with union but that didn't work. Can anybody help me?

Thanks!

This is how I would like the final table to look like: 在此处输入图片说明

You can use ALTER to add the last 3 columns to table 1. From there, INSERT table 2 onto table 1. So something like this.

ALTER table1 ADD dependent varchar(16)
ALTER table1 ADD favalue varchar(16)
ALTER table1 ADD probf varchar(16)

INSERT INTO table1(dependent, fvalue, probf)
  SELECT * FROM table2

You can use a combination of joins and unions

LEFT JOIN the two tables in first query on fields that won't have a match then UNION the second query with a RIGHT JOIN of the same tables.

The LEFT JOIN will only show results from the first table, then the RIGHT JOIN will only show results from the second

Something Like:

SELECT * FROM table1 as t1 
LEFT JOIN table1 as t2 on t1.variablenname = t2.fValue 
UNION 
SELECT * FROM table1 as t1 
RIGHT JOIN table1 as t2 on t1.variablenname = t2.fValue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM