1

我现在正在一个论坛上工作,我尝试创建一个概述,其中包含每个威胁的最新回复(如果存在)。

我有两张表,一张用于第一个线程,一张用于所有回复。

表 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
4

1 回答 1

1

试试这个(使用子选择):

select 
  t.id, 
  t.board,
  t.title,
  t.created,
  (select max(created) from replies r where r.thread = t.id) last_reply_date,
  coalesce((select max(created) from replies r where r.thread = t.id), t.created) last_activity_date  
from threads t

对于更大的查询,这可能会更快:

select 
  t.id,
  t.board,
  t.title,
  t.created,
  rg.created last_reply_date,
  coalesce(rg.created, t.created) last_activity_date
from threads t 
left join (select thread, max(created) created from replies r group by thread) rg
on rg.thread = t.id

编辑:

如果您想从相关表中检索多个字段,则不会那么容易:

select 
  t.id,
  t.board,
  t.title,
  t.created,
  r.created last_reply_date,
  coalesce(r.created, t.created) last_activity_date,
  r.author last_reply_author
from threads t 
left join (select thread, max(id) last_reply_id from replies group by thread) rg
on rg.thread = t.id
left join replies r
on r.id = rg.last_reply_id

本次选择:

select thread, max(id) last_reply_id from replies group by thread

负责创建线程的最后回复列表。我假设如果回复的 id 最高,它也是最新的。

所以在这个查询中,你用这个选择加入线程表,它只包含最后一个回复的 id,然后是回复表。

于 2013-06-01T18:29:18.230 回答