|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

谢谢
...全文
76 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
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
昵称被占用了 2007-12-28
  • 打赏
  • 举报
回复

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来关联起来

谢谢

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧