读书人

sql一对多表查询显示所有结果,该如何处

发布时间: 2012-03-01 10:25:46 作者: rapoo

sql一对多表查询显示所有结果
两个表
表A(信息表)

id,title,date

表B(评论表)

comid,infoid,detail,username (infoid对应表A中id)

现在要显示 表A的所有信息并与此信息对就的 最后一条 评论的信息

要显示 结果 为:

表A.ID 表A.TITLE 表A.DATE 表B.comid 表B.detail 表B.username

这语句要怎么写啊。

[解决办法]

SQL code
select * from 表A a,表B b where a.id=b.infoidand not exists(select 1 from 表B where infoid=b.infoid and comid>a.comid)
[解决办法]
SQL code
select * from 表A a,表B b where a.id=b.infoidand not exists(select 1 from 表B where infoid=b.infoid and comid>b.comid)
[解决办法]
SQL code
select a.id,a.title,a.date,b.comid,b.detail,b.usernamefrom 表A a left join 表B b on a.id=b.infoidwhere not exists(select 1 from 表B where infoid=b.infoid and comid>b.comid)
[解决办法]
SQL code
select  a.id,a.title,a.date,b.comid,b.detail,b.usernamefrom  表a a join 表b bon  a.id=b.infoidwhere  a.date=(select max(date) from 表a where id=a.id) 

读书人网 >SQL Server

热点推荐