每个论坛最新帖子的MySQL查询设计

时间:2010-07-03 20:54:06

标签: php sql mysql greatest-n-per-group

我有这3张桌子

forums_forum

+-----+--------+-------------+-------+-----+
| fid | name   | description | index | cid |
+-----+--------+-------------+-------+-----+
|  36 | gdghdf | hjghj       |    54 |   5 |
|  45 | yutuy  | iuyi        |    99 |   6 |
+-----+--------+-------------+-------+-----+

forums_threads

+----+-----+-----+-------+-------+------+-----------+------+
| id | tid | fid | moved | mfrom | view | important | lock |
+----+-----+-----+-------+-------+------+-----------+------+
|  1 |   4 |  36 |     0 | NULL  |    0 |         0 |    0 |
|  2 |  12 |  36 |     0 | NULL  |    7 |         0 |    0 |
|  3 |   9 |  15 |     0 | NULL  |    0 |         0 |    0 |
+----+-----+-----+-------+-------+------+-----------+------+

forums_posts

+----+-------+--------+--------+---------------------+--------+--------+-----+
| id | title | detail | author | date                | edited | editby | tid |
+----+-------+--------+--------+---------------------+--------+--------+-----+
|  1 | asfsd | sdfsd  |      1 | 2010-07-01 21:31:29 |      0 | NULL   |   4 |
+----+-------+--------+--------+---------------------+--------+--------+-----+

我正在尝试创建返回结果的查询 - >对于每个独特的'fid',来自'forums_posts'的一行(ORDER BY'日期')。

forums_forumfid = forums_threadsfid forums_threadstid = forums_poststid

由于

3 个答案:

答案 0 :(得分:3)

这是Stack Overflow上经常出现的令人尊敬的最大n组问题。这是给出表格的解决方案:

SELECT p.* FROM forums_posts p JOIN forums_threads t ON p.tid = t.tid
WHERE NOT EXISTS (
    SELECT * FROM forums_posts p2 JOIN forums_threads t2 ON p2.tid = t2.tid
    WHERE t.fid = t2.fid AND p.date < p2.date
);

答案 1 :(得分:1)

我建议你加入一些JOIN。

SELECT C.date, C.title, A.name
FROM forums_forum A 
   JOIN forums_threads B ON A.fid=B.fid 
   JOIN forums_posts C ON B.tid=C.tid
ORDER BY C.date DESC LIMIT 1

或..未经测试:

SELECT MAX(c.date), C.date, C.title, A.name
FROM forums_forum A 
   JOIN forums_threads B ON A.fid=B.fid 
   JOIN forums_posts C ON B.tid=C.tid
LIMIT 1

- )

P.S。通过命名列“日期”以及“索引”和“视图”可能会遇到麻烦,更好地使用其他名称。

p.p.s。是否存在fids(我认为这是你的主键并且应该是唯一的)哪一次出现更多?

答案 2 :(得分:0)

替代JOIN,您可以在forums_forums表格中添加一个名称为last_updated的列。在线程的每个帖子中,只需运行一个额外的UPDATE之类的。

  

UPDATE论坛SET last_updated = NOW()

然后,为了按论坛的顺序获取论坛,您的SELECT变得更加简单和高效。

  

SELECT * FROM forums_forum ORDER BY last_updated DESC