我有两张表如下:
Mail_Thread
-------------
id,
thread_name,
created
,
Mail
----
id,
thread_id (FK for Mail_thread),
to,
subject,
message,
created
这里一个帖子包含多个邮件。所以我希望结果是使用join的不同线程和该线程的最后一条消息。那有什么可能吗?
答案 0 :(得分:2)
您可以通过MySQL中的一系列连接来实现此目的。第一个连接将线程连接到邮件消息,第二个连接将这些邮件限制为每个线程的最新邮件。
SELECT t1.thread_name,
t2.message
FROM Mail_Thread t1
INNER JOIN Mail t2
ON t1.id = t2.thread_id
INNER JOIN
(
SELECT thread_id, MAX(created) AS max_created -- this subquery identifies
FROM Mail -- the most recent message
GROUP BY thread_id -- for each thread
) t3
ON t2.thread_id = t3.thread_id AND
t2.created = t3.max_created
答案 1 :(得分:0)
select mt.id,mt.thread_name,mt.created
from mail_thread mt
inner join mail m on mt.id =m.thread_id
group by m.thread_id
order by mt.created desc