简体   繁体   中英

Joining Multiple unrelated tables but the same columns

I'm trying to join 5-6 tables which has the same columns but the data isn't related. For example, Table 1 contains Customer 1,2,3 - Table 2 contains Customer 4,5,6 and so on but none of them containts the same Customer. How can I join these 6 tables and get all the data in one table?

Hoping, I understood your question correctly.

Please check below script.

Sql fiddle link: http://sqlfiddle.com/#!18/d2396/1

create table customer_1
(
cust_id int
);

insert into customer_1 values(1);
insert into customer_1 values(2);
insert into customer_1 values(3);

create table customer_2
(
cust_id int
);

insert into customer_1 values(4);
insert into customer_1 values(5);
insert into customer_1 values(6);

create table customer_3
(
cust_id int
);

insert into customer_1 values(7);
insert into customer_1 values(8);
insert into customer_1 values(9);


select cust_id from customer_1
union all
select cust_id from customer_2
union all
select cust_id from customer_3;

If you are looking for a combined table with all users under the same columns, use UNION OR UNION ALL. If some of the tables are missing columns, you could just enter null in the select list:

https://msdn.microsoft.com/en-us/library/ms180026(v=sql.90).aspx

If not, you can CROSS JOIN them or use some parent-child join logic.

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