一个简单的查询 在线

zhouzhijian888 2008-11-01 06:23:11
我有3个表 数据的行数 都一样 但是列名不一样
我想把 3个表的结果 都组织到一起 组成个新的结果集
需要怎么做
...全文
117 15 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
wujumao 2008-11-02
  • 打赏
  • 举报
回复
保证每一个子结果集的字段名,字段类型 一致。
lihuanmei 2008-11-01
  • 打赏
  • 举报
回复
select *,id=identity(int,1,1) into #1 from a
select *,id=identity(int,1,1) into #2 from b
select *,id=identity(int,1,1) into #3 from c
select 名字=#1.name,年龄=#2.age,地址=#3.dress
into #
from #1 inner join #2 on #1.id=#2.id inner join #3 on #1.id=#3.id
order by #1.id
select * from #
drop table #1
drop table #2
drop table #3
drop table #
lihuanmei 2008-11-01
  • 打赏
  • 举报
回复
select *,id=identity(int,1,1) into #1 from a
select *,id=identity(int,1,1) into #2 from b
select *,id=identity(int,1,1) into #3 from c
select name,age,dress
into #
from #1 inner join #2 on #1.id=#2.id inner join #3 on #1.id=#3.id
order by #1.id
ljhcy99 2008-11-01
  • 打赏
  • 举报
回复

假设 ta 有 aa1 ,bb1字段, tb 有 aa2 ,bb2字段, tc 有 aa3 ,bb3字段,


select ta.aa1 as A,ta.bb1 As B from ta
union all
select tb.aa2 as A,tb.bb2 As B from tb
union all
select tc.aa3 as A,tc.bb3 As B from tc


保证每一个子结果集的字段名,字段类型 一致。
lihuanmei 2008-11-01
  • 打赏
  • 举报
回复
我想应该对每一个表加标识符,例如ID=identity()
-晴天 2008-11-01
  • 打赏
  • 举报
回复
create table tb1(id int,cola int,othercol varchar(10))
insert into tb1 select 4,7,'fasd'
insert into tb1 select 7,5,'fwe'
create table tb2(id int,colb varchar(10),othercol varchar(10))
insert into tb2 select 3,'as','vwe'
insert into tb2 select 5,'mnivw','fwe'
--设两表都由id列排序:
select t1.cola,t2.colb from
(select cola,(select count(*) from tb1 where id<=a.id) as id0 from tb1 a)t1 inner join
(select colb,(select count(*) from tb2 where id<=b.id) as id0 from tb2 b)t2
on t1.id0=t2.id0
go
drop table tb1,tb2
/*
cola colb
----------- ----------
7 as
5 mnivw

(2 行受影响)
*/
-晴天 2008-11-01
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 qianjin036a 的回复:]
可以,但得有个排列依据.
[/Quote]
列几条真实的数据看看,注意有没有ID列.
zhouzhijian888 2008-11-01
  • 打赏
  • 举报
回复
没有满意的 union 不能用!~~~
zhouzhijian888 2008-11-01
  • 打赏
  • 举报
回复
不是 是把 数据 并排起来就行 不合并
例如
a 表 b表 c表
name age dress
1 3 as
2 5 dssf
3 6 dasdf
我只要表中指定的列 其他列 我不要 数据的行数是相等的
zhouzhijian888 2008-11-01
  • 打赏
  • 举报
回复
包含 UNION 运算符的 SQL 语句中的所有查询都必须在目标列表中具有相同数目的表达式。



-晴天 2008-11-01
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 zhouzhijian888 的回复:]
我试试 可以的话 我就结贴
[/Quote]
听你的意思是把数据排到同一行里?
zhouzhijian888 2008-11-01
  • 打赏
  • 举报
回复
我试试 可以的话 我就结贴
-晴天 2008-11-01
  • 打赏
  • 举报
回复
可以,但得有个排列依据.
jiangshun 2008-11-01
  • 打赏
  • 举报
回复
新建一个表,然后分别把着三个表中的数据导进去就可以了
水族杰纶 2008-11-01
  • 打赏
  • 举报
回复
select * from ta
union all
select * from tb
union all
select * from tc

34,838

社区成员

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

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