我现在正在一个论坛上工作,我尝试创建一个概述,其中包含每个威胁的最新回复(如果存在)。
我有两张表,一张用于第一个线程,一张用于所有回复。
表 1(线程)
id、board、title、text、created...
表 2(回复)
id、board、thread、title、text、created...
现在我正在尝试选择每个线程,如果存在,则从最新回复中选择“创建”字段。
所以我想有类似的东西:
SELECT a.id, a.id as thread, a.title, a.created FROM a IF entry in b with b.thread = a.id use latest b.created
这是解决方案(感谢 LukLed)
SELECT
a.id,
a.title,
COALESCE(b.created, a.created) created,
COALESCE(b.author, a.author) author
FROM forum_threads a
LEFT JOIN (SELECT thread, max(id) id FROM forum_replies GROUP BY thread) c on c.thread = a.id
LEFT JOIN forum_replies b on b.id = c.id
WHERE a.board = '".data::escape($id)."'
ORDER BY created DESC