一个sql多表查询的问题

来源:百度知道 编辑:UC知道 时间:2024/08/24 19:41:03
有两个表,比如a表是会员信息,b表是会员发的帖子
每个会员会发多条帖子
我想通过一条语句查询所有会员发的最后一条帖子
select a.id,count(b.ft) from a,b where a.id=b.id group by a.id
count(b.ft)这个是发的帖子数吧?
我要的是最后一条帖子,比如b.title
但是要过滤剩下 每个用户最后发表的一条帖子,其他帖子不要
不知道我说明白没有

a 表 id,username b 表 userid,title,content

受到大家的启发找到一个方法:
select t1.* from (select b.title,b.content,a.id,a.username from a,b where a.id=b.userid and username like '%abc%' and b.title='%bcd%') t1,
(select userid,max(pdate) as pdate from b
group by userid) t2 where t1.id=t2.userid and t1.pdate=t2.pdate

思路是先联合查a,b表找到符合条件的所有数据,然后列出所有用户的最新帖子的发布人id和帖子发布时间,再对比两组数据,找到重合的数据
不知道还有没有更简单执行效率更高的

lz给的表信息不全
假设有一个时间字段记录每次发帖时间
a表和b表靠会员信息ID相连
语句如下
select b.*
from (select b.id,max(b.time) time from b join a on a.id=b.id
group by b.id) t join b on b.id=t.id and b.time=t.time

select a.id,count(b.ft) from a,b where a.id=b.id group by a.id

select * from a left join b on a.id=b.id group by a.id;
自动列出最新一条记录

豆花正解

select b.* from(select b.userid,max(b.updatetime) time from b join a on a.id=b.userid group by b.userid) t join b on b.userid=t.userid and b.updatetime=t.time

SELECT a.id,b.title,b.content
FROM a
INNER JOIN b ON a.id = b.uid
ORDER BY b.id DESC
GROUP BY a.id

select * from (
select row_number() over(partition by a.会员信息 order by timest desc) as orders,timest,a.会员信息,b.发帖id
from (select timest,a.会员信息,b.发帖id from
a,b where a.会员信息=b.会员信息 group by a.会员信息,timest,b.发帖id order by timest desc) a) a
where a.orders<2;

timest是发帖时间,大概就是这个意思你看看行不行

豆花的