SQL语句难题,高手进来!!

cbzdream 2003-10-17 10:51:42
有表A1(主表),B1(从表),通过字段ID相关联。
A表 B表

字段ID(主键) 字段ID

1 1
2 1
3 2
2
。。。。 3
3
。。。。。

要得出的记录集是:字段ID=1的任意一条记录,字段ID=2的任意一条记录,字段ID=3的任意一条记录。。。。。。。。。。。

记录集中要包括A,B表的所有字段。




...全文
63 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
LoveSQL 2003-10-17
  • 打赏
  • 举报
回复

select top 1 a.*, b.* from a,b where a.id=b.id
LoveSQL 2003-10-17
  • 打赏
  • 举报
回复

select a.*,b.* into #tep from a,b where a.id=b.id
select top 1* from #tep
cbzdream 2003-10-17
  • 打赏
  • 举报
回复
A,B两表都有其他字段,请问一句SQL能求出想要的记录集吗?
zjcxc 元老 2003-10-17
  • 打赏
  • 举报
回复
--下面是数据测试:

declare @A1 table(id int,a int)
insert into @A1
select 1,22
union all select 2,33
union all select 3,44
union all select 4,55

declare @B1 table(id int,b int)
insert into @b1
select 1,3
union all select 1,4
union all select 2,5
union all select 2,6
union all select 2,7
union all select 2,8
union all select 3,9
union all select 3,10
union all select 3,11
union all select 1,12
union all select 2,13

select myid=identity(int,1,1),* into #tb from @b1

select * from @a1 a inner join #tb b on a.id=b.id
and b.myid=(select min(myid) from #tb where id=a.id)

drop table #tb

/*--测试结果

id a myid id b
----------- ----------- ----------- ----------- -----------
1 22 1 1 3
2 33 3 2 5
3 44 7 3 9

(所影响的行数为 3 行)
--*/
zjcxc 元老 2003-10-17
  • 打赏
  • 举报
回复
--如果B1表中还包含其他字段,就改用临时表.

--创建临时表
select myid=identity(int,1,1),* into #tb from B1

--查询结果
select * from A1 a inner join #tb b on a.id=b.id
and b.myid=(select min(myid) from #tb where id=a.id)

--删除临时表
drop table #tb
zjcxc 元老 2003-10-17
  • 打赏
  • 举报
回复
--没错啊,你看测试:

declare @A1 table(id int)
insert into @A1
select 1
union all select 2
union all select 3
union all select 4

declare @B1 table(id int)
insert into @b1
select 1
union all select 1
union all select 2
union all select 2
union all select 2
union all select 2
union all select 3
union all select 3
union all select 3
union all select 1
union all select 2

select *,(select top 1 * from @b1 where a.id=id) from @a1 a
allenq 2003-10-17
  • 打赏
  • 举报
回复
select a.*, b.* from a right join b
on a.id = b.id
where b.id in( 1,2,3)

right join返回b表的所有记录.
cbzdream 2003-10-17
  • 打赏
  • 举报
回复
有错误:
当没有用 EXISTS 引入子查询时,在选择列表中只能指定一个表达式。
yujohny 2003-10-17
  • 打赏
  • 举报
回复
select *,(select top 1 * from B where id=A.id) from A
伍子V5 2003-10-17
  • 打赏
  • 举报
回复
select a.*,(select top 1 b.* from b where ID=a.ID) from a
cbzdream 2003-10-17
  • 打赏
  • 举报
回复
高手呢?
shuiniu 2003-10-17
  • 打赏
  • 举报
回复
回复人: cbzdream(迷茫) ( ) 信誉:90 2003-10-17 11:14:00 得分:0


有错误:
当没有用 EXISTS 引入子查询时,在选择列表中只能指定一个表达式。
---------------------------------------------------------------------
select a.* ,(select top 1 表b的第一列 from b where a.id = b.id), ....,(select top 1 表b的最后一列 from b where a.id = b.id) from a

表b中的列很多时,可动态生成上面的语句!

34,576

社区成员

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

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