导航
  • 主页
  • 基础类
  • 应用实例
  • 新技术前沿

|M| 求SQL语句 多表进行合并

zyciis628 2007-12-28 03:48:27
表A
ID name Address
1 Jerry GuanZhuo
表B
ID Name Address
1 Joy ShanHai

表C
OrderID Name
1 Jerry
2 Joy

因为系统有两个用户表和一个订单表设计的很不好的,但现在要查询出订单表中他们的地址结果为

OrderID Name ID Address
1 Jerry 1 GuanZhuo
2 Joy 1 ShanHai

谢谢
...全文
36 点赞 收藏 7
写回复
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
hpx021131 2007-12-28
老乌龟果然是老乌龟

速度快。 呵呵...
回复
dawugui 2007-12-28
create table A(ID int,name varchar(10),Address varchar(10))
insert into A values(1, 'Jerry', 'GuanZhuo' )
create table B(ID int,name varchar(10),Address varchar(10))
insert into B values(1, 'Joy', 'ShanHai ' )
create table c(OrderID int,Name varchar(10))
insert into c values(1, 'Jerry')
insert into c values(2, 'Joy')
go

select c.* , t.id , t.address
from c left join (select * from a union all select * from b) t
on c.name = t.name

drop table a,b,c

/*
OrderID Name id address
----------- ---------- ----------- ----------
1 Jerry 1 GuanZhuo
2 Joy 1 ShanHai

(2 行受影响)
*/
回复
liangCK 2007-12-28
select a.*,b.id,b.address 
from 表C a,
(select id,name,address from 表A union all select id,name,address from 表B) b
where a.name=b.name
回复

select c.*,
isnull(a.id,b.id) as id,
isnull(a.Address,b.Address ) as Address
from c left join a on c.name=a.name
left join b on c.name=b.name


回复
liangCK 2007-12-28
select a.*,b.id,b.address
from 表C a,
(select name,address from 表A union all select name,address from 表B) b
where a.name=b.name
回复
dawugui 2007-12-28
select c.* , t.id , t.address
from c left join (select * from a union all select * from b) t
on c.name = t.name
回复
zyciis628 2007-12-28
也就是说要表A和表B的数据相结合再和表C用Name来关联起来

谢谢
回复
发动态
发帖子
MS-SQL Server
创建于2007-09-28

3.2w+

社区成员

MS-SQL Server相关内容讨论专区
申请成为版主
社区公告
暂无公告