急!!!关于联合查询的问题!!!
求1条Sql语句
a ,b2个表
a表数据
id name
1 力量
2 往往
3 饿额
b表数据
id title key
1 亲切 WW
1 常常 DD
1 爸爸 CC
2 天天 GG
2 哦哦 BB
3 批评 NN
3 可靠 MM
现在用Sql语句
要得出下面的结果(id列关联2个表)
id title key
1 亲切 WW
2 天天 GG
3 批评 NN
结果不限定为每个ID的第1条记录,但是ID必须是对应的
也可以是
id title key
1 常常 DD
2 哦哦 BB
3 可靠 MM
[解决办法]
- SQL code
select * from b a where not exists(select 1 from b where id=a.id and title>a.title)
[解决办法]
- SQL code
select * from bwhere not exists(select 1 from b t where id=b.id and title>b.title)
[解决办法]
- SQL code
select * from b a where not exists(select 1 from b where id=a.id and key <a.key)
[解决办法]
- SQL code
select * from b a where not exists(select 1 from b where id=a.id and title>a.title)
[解决办法]
- SQL code
declare @a table(id int,name nvarchar(20))insert into @aselect 1,N'力量'unionselect 2,N'往往'unionselect 3,N'饿额'declare @b table(id int,title nvarchar(10),key1 varchar(10))insert into @bselect 1,N'亲切','WW'unionselect 1,N'常常','DD'unionselect 1,N'爸爸','CC'unionselect 2,N'天天','GG'unionselect 2,N'哦哦','BB'unionselect 3,N'批评','NN'unionselect 3,N'可靠','MM'select * from @b gwhere not exists(select 1 from @b f where f.id=g.id and f.title>g.title)and g.id in (select id from @a)
[解决办法]
- SQL code
declare @a table (id int,name varchar(10))insert into @a select 1,'力量'insert into @a select 2,'往往'insert into @a select 3,'饿额'declare @b table (id int,title varchar(10),[key] varchar(10))insert into @b select 1,'亲切','WW'insert into @b select 1,'常常','DD'insert into @b select 1,'爸爸','CC'insert into @b select 2,'天天','GG'insert into @b select 2,'哦哦','BB'insert into @b select 3,'批评','NN'insert into @b select 3,'可靠','MM'select * from @a a,(select id,title=(select top 1 title from @b where id=b.id order by newid()),[key]=(select top 1 [key] from @b where id=b.id order by newid()) from @b b group by id) bwhere a.id=b.id
[解决办法]
newid()
[解决办法]
- SQL code
select a.id,b1.title,b1.[key]from a left join b b1 on a.id=b1.id where (select count(1) from b where [key]<=b1.[key] and id=b1.id)=(select count(1) from b where id=b1.id)-1
[解决办法]
- SQL code
select a.id,(Select top 1 title from @b where id = a.id) title,(select top 1 key1 from @b where id = a.id) key1from @a a