0

我喜欢为我的网站制作论坛预告片。只显示最新的帖子或线程很容易。我喜欢在同一个查询中获取最新的线程和帖子,按最后一个活动排序。因此,它将按 REPLY TO POST 日期和 THREAD POST 日期在同一查询中排序。我认为这与您如何对它进行分组有关,但我不确定。

线程

id, header, text, date, author

帖子

id, text, date, author, thread_id

使用示例

20分钟前——如何制作php/mysql脚本(二)

17 分钟前 - 请帮帮我 (0)

1 小时前 - 我需要 PHP 方面的帮助 (1)

如您所见,已回答的线程和新线程都在列表中。(我需要最新回复的日期或创建时间、标题和回复的计数())

我希望你得到,并知道如何做到这一点。

巨魔

更新:

我有这个,没关系,但我只收到带有回复的线程。

SELECT 
    threads.*, 
    posts.*, 
    (SELECT date FROM posts WHERE thread_id = threads.id ORDER BY date DESC LIMIT 0,1) AS postdate, 
    (SELECT count(id) FROM threads WHERE thread_id = thread.id) AS replys 
FROM 
    threads, 
    posts 
WHERE 
    threads.id = posts.thread_id
GROUP BY 
    thread_id
ORDER BY 
    postdate DESC, 
    thread.date 
LIMIT 
    0,15

我怎样才能做到这一点?

更新

啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊!!!!

我自己设法做到了:-) 花了一段时间才把它做好。

SELECT 
    fisk_debat.id, 
    fisk_debat.dato,
    IF((SELECT count(id) FROM fisk_debat_svar WHERE debatid = fisk_debat.id) < 1, fisk_debat.dato, (SELECT dato FROM fisk_debat_svar WHERE debatid = fisk_debat.id ORDER BY dato DESC LIMIT 0,1)) AS svardato,
    fisk_debat.overskrift,
    (
    SELECT count(fisk_debat_svar.debatid) 
    FROM fisk_debat_svar 
    WHERE fisk_debat_svar.debatid = fisk_debat.id
    ) AS svar

FROM  fisk_debat
GROUP BY  id
UNION
SELECT
    fisk_debat_svar.debatid AS id, 
    max(fisk_debat_svar.dato) AS dato,
    max(fisk_debat_svar.dato) AS svardato,
    (
    SELECT fisk_debat.overskrift 
    FROM fisk_debat 
    WHERE fisk_debat.id = fisk_debat_svar.debatid
    ) AS overskrift,
    (
    SELECT count(fisk_debat_svar.debatid) 
    FROM fisk_debat_svar 
    WHERE fisk_debat_svar.debatid = id
    ) AS svar

FROM fisk_debat_svar
WHERE id != id
GROUP BY id

ORDER BY svardato DESC, dato DESC
LIMIT 0,15
4

2 回答 2

0

如果要保留当前的数据库结构,则需要一个 Union 来获得所需的结果。可以在http://www.mysqltutorial.org/sql-union-mysql.aspx找到一个示例

但是,我仍然建议按照对您问题的评论中的说明更改结构。

于 2011-05-16T12:26:47.467 回答
0

WHERE子句只选择有回复的线程,这是正常的。您必须使用LEFT JOIN语法。

尝试这个:

SELECT 
    threads.*, 
    posts.*, 
    (SELECT date FROM posts WHERE thread_id = threads.id ORDER BY date DESC LIMIT 0,1) AS postdate, 
    (SELECT count(id) FROM threads WHERE thread_id = thread.id) AS replys 
FROM 
    threads
LEFT JOIN
    posts
ON
    threads.id = posts.thread_id
ORDER BY 
    postdate DESC, 
    thread.date 
LIMIT 
    0,15
于 2011-05-16T12:29:06.090 回答