如果条目已存在,请使用第二个表中的字段

时间:2013-06-01 18:21:25

标签: mysql sql select join

我现在正在论坛上工作,如果存在,我会尝试使用每个威胁的最新回复创建一个概述。

我有两个表,一个用于第一个帖子,一个用于所有回复。

TABLE1 (THREADS)

id,board,title,text,created ...

TABLE2 (REPLIES)

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

1 个答案:

答案 0 :(得分:1)

试试这个(使用subselect):

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最高,它也是最新的。

因此,在此查询中,您将使用此select连接线程表,该select仅包含最后一次回复的ID,然后包含回复表。