求一条SQL查询语句

xjchen 2006-02-22 05:29:49
两张表 users 和 news 关联
users里的用户可以发布信息保存在news里
现在要取出一个记录集, 要求返回news 里的记录, 但每个用户最多取10条信息,要如何去写这个查询语句?
...全文
78 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
dulei115 2006-02-22
  • 打赏
  • 举报
回复
--测试数据,测试通过,不知道楼主的数据结构,楼主自己改
if object_id('table1') is not null drop table table1
go
select 1 as col1, 'a' as col2
into table1
union select 2, 'b'

if object_id('table2') is not null drop table table2
go
select 1 as col1, 'aa' as col2
into table2
union select 1, 'ab'
union select 1, 'ac'
union select 2, 'ba'
union select 2, 'bb'
union select 2, 'bc'
go

select a.col1, a.col2, b.col2
from table1 a join table2 b on a.col1 = b.col1
where b.col2 in (select top 2 col2 from table2 where col1 = a.col1)
/*
1 a aa
1 a ab
2 b ba
2 b bb
*/

drop table table1
drop table table2
dulei115 2006-02-22
  • 打赏
  • 举报
回复
测试数据,测试通过,不知道楼主的数据结构,楼主自己改
if object_id('table1') is not null drop table table1
go
select 1 as col1, 'a' as col2
into table1
union select 2, 'b'

if object_id('table2') is not null drop table table2
go
select 1 as col1, 'aa' as col2
into table2
union select 1, 'ab'
union select 1, 'ac'
union select 2, 'ba'
union select 2, 'bb'
union select 2, 'bc'
go

select a.col1, a.col2, b.col2
from table1 a join table2 b on a.col1 = b.col1
where b.col2 in (select top 2 col2 from table2 where col1 = a.col1)

drop table table1
drop table table2

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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