简体   繁体   English

连接多个不相关的表但列相同

[英]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. 我正在尝试联接5-6个具有相同列的表,但数据无关。 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. 例如,表1包含客户1,2,3-表2包含客户4,5,6,依此类推,但没有一个包含同一客户。 How can I join these 6 tables and get all the data in one table? 如何连接这6个表并在一个表中获取所有数据?

Hoping, I understood your question correctly. 希望我能正确理解您的问题。

Please check below script. 请检查以下脚本。

Sql fiddle link: http://sqlfiddle.com/#!18/d2396/1 SQL小提琴链接: 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. 如果要在所有列下查找所有用户的组合表,请使用UNION或UNION ALL。 If some of the tables are missing columns, you could just enter null in the select list: 如果某些表缺少列,则可以在选择列表中输入null:

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

If not, you can CROSS JOIN them or use some parent-child join logic. 如果没有,您可以交叉连接它们或使用某些父子连接逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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