我想获得几个类别中的5个最新活动主题。每个主题都有一个subcatid,这个subcatid与catid有关。
我想要的是在每个catid中获得5个活跃主题。
我正在尝试使用下面的查询,但这根本不起作用:
set @num := 0, @catid := 0;
SELECT
forum_posts.topicid,
forum_topics.titel,
forum_topics.sticky,
forum_topics.gesloten,
MAX(forum_cats.id) AS catid,
MAX(forum_cats.titel) AS cattitel,
MAX(forum_subcats.id) AS subcatid,
MAX(forum_posts.id) AS maxid,
DATE_FORMAT(MAX(forum_posts.datum), '%d-%m-%Y om %H:%i uur') AS datum,
UNIX_TIMESTAMP(MAX(forum_posts.datum)) AS laatstereactieunix,
(COUNT(forum_posts.id) - 1) AS reactieaantal,
@num := IF(@catid = MAX(forum_cats.id), @num + 1, 1) AS row_number,
@catid := MAX(forum_cats.id) AS dummy
FROM
forum_posts
INNER JOIN
forum_topics
ON
forum_topics.id = forum_posts.topicid
INNER JOIN
forum_subcats
ON
forum_subcats.id = forum_topics.subcat
INNER JOIN
forum_cats
ON
forum_cats.id = forum_subcats.cat
WHERE
forum_cats.id IN (1)
AND
forum_topics.gesloten != '1'
GROUP BY
forum_posts.topicid,
forum_topics.titel,
forum_topics.sticky,
forum_topics.gesloten
HAVING
row_number <= 5
ORDER BY
forum_cats.id ASC,
MAX(forum_posts.datum) DESC
执行此代码时,我总是得到row_number的相同数字(1),所以这不是我想要的结果。
有谁知道如何才能完成这项工作?
谢谢!
答案 0 :(得分:0)
尝试这个简化的查询,如果它返回了你想要的东西,那么你可以添加其他所需的列:
set @num := 0, @id := 0;
SELECT
forum_cats.id
forum_topics.id,
@id:=if(@id > forum_topics.id, @id, forum_topics.id) , -- the latest forum_topics.id for each category
@num := IF(@id = forum_topics.id, 1, @num + 1) AS row_number
FROM
forum_posts
INNER JOIN
forum_topics
ON
forum_topics.id = forum_posts.topicid
INNER JOIN
forum_subcats
ON
forum_subcats.id = forum_topics.subcat
INNER JOIN
forum_cats
ON
forum_cats.id = forum_subcats.cat
WHERE
forum_cats.id IN (1,3,5)
AND
forum_topics.gesloten != '1'
GROUP BY
forum_cats.id,
forum_topics.id
ORDER BY
forum_cats.id ASC,
MAX(forum_posts.datum) DESC
答案 1 :(得分:0)
我在MySQL中只尝试了两个类似的东西,得到了一些非常奇怪的结果。首先,查询中的变量赋值是错误的(至少,如果我解释你想要实现的目标)。
首先替换:
@num := IF(@catid = MAX(forum_cats.id), @num + 1, 1) AS row_number,
@catid := MAX(forum_cats.id) AS dummy
与
@num := IF(@catid = forum_cats.id, @num + 1, 1) AS row_number,
@catid := forum_cats.id AS dummy
但奇怪的是,如果你在row_number上没有任何过滤的情况下运行查询,你会得到预期的结果(即每个论坛类别得到一个row_number)。但是当添加有限制时,你会注意到row_number会突然跳过2(例如,如果你有3个类别,row_number将是1,3,5而不是1,2,3)。您可以使用having row_number < 10
代替having row_number <= 5
来获得预期结果。
btw我在Windows上的MySQL 5.0.51b中得到了这种奇怪的行为,我在Ubuntu上的MySQL 5.1.41中也是如此,所以我猜这是一个bug ......
哦,顺便说一下你的查询的其余部分一定是错的(你应该把所有的MAX(...)都丢弃为...),并且@ceteras是对的,你最好简单地开始并扩展你的查询走。我注意到的奇怪之处显然可以通过添加ORDER BY子句来解决(参见图)。