日期:2014-05-18  浏览次数:20611 次

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.infoid
and 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.infoid
and 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.username
from 表A a left join 表B b on a.id=b.infoid
where 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.username
from
  表a a join 表b b
on
  a.id=b.infoid
where
  a.date=(select max(date) from 表a where id=a.id)