求一条sql语句

netboygg 2013-07-25 01:40:23
现有2张表 tb1、tb2:

CREATE TABLE [dbo].[tb1](
[tb1order] [int] NULL,
[tb2name] [varchar](50) NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[tb2](
[tb2name] [varchar](50) NULL
) ON [PRIMARY]
GO

tb1 之中数据为
INSERT INTO tb1(tb1order,tb2name) VALUES (1,'a')
INSERT INTO tb1(tb1order,tb2name) VALUES (2,'a')
INSERT INTO tb1(tb1order,tb2name) VALUES (3,'a')
INSERT INTO tb1(tb1order,tb2name) VALUES (1,'b')
INSERT INTO tb1(tb1order,tb2name) VALUES (2,'b')
INSERT INTO tb1(tb1order,tb2name) VALUES (3,'b')

tb2 之中数据为
INSERT INTO tb2 (tb2name) VALUES('a')
INSERT INTO tb2 (tb2name) VALUES('b')


现想得到如下结果:查出tb2中name在tb1中order 最小的值

tb1order tb2name
1 a
1 b

谢谢了~!
...全文
79 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
netboygg 2013-07-25
  • 打赏
  • 举报
回复
引用 4 楼 netboygg 的回复:
[quote=引用 1 楼 hdhai9451 的回复:]

select b.tb1order,a.tb2name 
from tb2 a
left join tb1 b on a.tb2name=b.tb2name
where b.tb1order in(select MIN(tb1order) from tb1)

/*
1	a
1	b
*/
不过有问题啊。。。貌似没有解决 用:
select b.tb1order,a.tb2name 
from tb2 a
left join tb1 b on a.tb2name=b.tb2name
where b.tb1order in(select MIN(tb1order) from tb1)
tb1里的tb1order 如果不都是1,2,3的话就返回不了正确的结果。 比如说是 tb1: 2 a 3 a 7 a 4 b 5 b 8 b 那么返回的结果是 2 a 正确的应该是 2 a 4 b 求解???[/quote] 知道了 在里面加一句 group by tb2name
select b.tb1order,a.tb2name 
from tb2 a
left join tb1 b on a.tb2name=b.tb2name
where b.tb1order in(select MIN(tb1order) from tb1 GROUP BY tb2name)
netboygg 2013-07-25
  • 打赏
  • 举报
回复
引用 1 楼 hdhai9451 的回复:

select b.tb1order,a.tb2name 
from tb2 a
left join tb1 b on a.tb2name=b.tb2name
where b.tb1order in(select MIN(tb1order) from tb1)

/*
1	a
1	b
*/
不过有问题啊。。。貌似没有解决 用:
select b.tb1order,a.tb2name 
from tb2 a
left join tb1 b on a.tb2name=b.tb2name
where b.tb1order in(select MIN(tb1order) from tb1)
tb1里的tb1order 如果不都是1,2,3的话就返回不了正确的结果。 比如说是 tb1: 2 a 3 a 7 a 4 b 5 b 8 b 那么返回的结果是 2 a 正确的应该是 2 a 4 b 求解???
zhangyisc 2013-07-25
  • 打赏
  • 举报
回复
学习了,一致都在困惑这个东东。
netboygg 2013-07-25
  • 打赏
  • 举报
回复
谢谢哦~~~
Andy__Huang 2013-07-25
  • 打赏
  • 举报
回复

select b.tb1order,a.tb2name 
from tb2 a
left join tb1 b on a.tb2name=b.tb2name
where b.tb1order in(select MIN(tb1order) from tb1)

/*
1	a
1	b
*/

34,590

社区成员

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

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