我使用sql请求通过论坛按用户获取号码消息。
SELECT count(idpost), iduser, idforum
FROM post
group by iduser, idforum
答案 0 :(得分:2)
根据编辑过的问题:
请尝试以下查询。我们需要的是一个子查询基于idforum查找max(idpost)。请考虑以下查询:
select max(idpost) as IDPOST,idforum
from post
group by idforum
此查询应该做的是查找用户在论坛上发布的帖子数量。因此它应该为您提供如下输出:
idpost idforum
3 1
2 2
3 4
然后我们需要为这些行找到相关的iduser:
select p2.IDPOST, p1.iduser, p2.idforum
from post p1 inner join
( --the query above comes here as subquery.
select max(idpost) as IDPOST,idforum
from post
group by idforum
) p2 on p1.idforum = p2.idforum and p1.idpost = p2.IDPOST
它正在做的是根据idforum和idpost值将主表中的数据与来自子查询的temprorary数据进行匹配,并添加原始表中的iduser值。
idpost iduser idforum
3 2 1
2 6 2
3 2 4
答案 1 :(得分:1)
SELECT count(idpost) MAX,iduser,idforum FROM post
ORDER BY count(idpost) DESC group by iduser,idforum
或者,您可以执行嵌套查询。但是,我更喜欢这个。 您可以轻松选择第一个结果为MAX
答案 2 :(得分:1)
SELECT MAX(CN),idforum,Max(iduser) iduser
FROM (
SELECT count(idpost) CN,iduser,idforum
FROM post
Group By iduser,idforum
) A Group By idforum
答案 3 :(得分:1)
假设您提供有问题的论坛的idForum .........只需按照计数desc查询您的查询的第一行
SELECT TOP 1 * FROM
(
SELECT count(idpost),iduser,idforum FROM post
GROUP BY iduser,idforum
) PostsCount
WHERE PostsCount.idForum = @theForumIdIamLookingFor
ORDER BY count DESC