我很困惑多次加入同桌 例如:我得到了以下表格
create table #cust (id int , name varchar(50) )
insert into #cust values (111, 'john')
create table #addfrom (addid int , address varchar(50) )
insert into #addfrom values (111, '11,st')
insert into #addfrom values (111, '12,st')
insert into #addfrom values (111, '13,st')
create table #reg (regid int , reg varchar(50) )
insert into #reg values (111, 'nissan')
insert into #reg values (111, 'hyhun')
insert into #reg values (111, 'kia')
insert into #reg values (111, 'bmw')
当我单独加入时:
select
c.*
from
#cust c join #addfrom a on c.id = a.addid
- 3行
select
c.*
from
#cust c join #reg r on c.id = r.regid
- 4行
但是当我加入时如下:
select
c.*
from
#cust c
join #addfrom a on c.id = a.addid
join #reg r on c.id = r.regid
我有12行,但我期待7行。我该怎么办? 提前谢谢。
答案 0 :(得分:0)
这可能会有所帮助
select * from #cust c
union
select * from #addfrom a
union
select * from #reg r
答案 1 :(得分:0)
您可以执行联接产生的两个表中的UNION
select
c.*, r.*
from
cust c
join reg r on c.id = r.regid
UNION
select
c.*, a.*
from
cust c
join addfrom a on c.id = a.addid
只要两个表具有相同的列数。如果要了解数据,可能需要定义新列(在第一个和第二个连接中)。