我有以下表格:
tasks ( id int PRIMARY KEY auto_increment,
description text,
created datetime,
modified datetime);
commentaries( id int PRIMARY KEY auto_increment,
task_id int,
user_id int,
description text,
created datetime );
users ( id int PRIMARY KEY auto_increment,
name varchar(300),
created datetime );
这是一对多关系(1-N)。
我正在构建一个收件箱,列出最后N个任务,并显示每个任务的最后插入的评论?
EDIT1 :
查询:
SELECT T.id, T.description, C.description, T.created
FROM tasks T LEFT JOIN commentaries C ON T.id = C.task_id AND C.id IN (
SELECT max(C.id) FROM tasks Task
LEFT JOIN commentaries C ON C.task_id = Task.id
WHERE Task.id in (select id from tasks WHERE user_id = 1 )
GROUP BY Task.id)
ORDER BY T.id DESC
LIMIT 10;
EDIT2
SQL小提琴链接:http://sqlfiddle.com/#!2/1555c7/1
答案 0 :(得分:1)
您可以使用以下方式获取上次插入评论的时间:
select task_id, max(created) as maxc
from commentaries
group by task_id;
您可以在join
中使用此评论来获取最后插入的评论:
select t.*, c.*
from tasks t join
commentaries c
on c.task_id = t.id join
(select task_id, max(created) as maxc
from commentaries
group by task_id
) cmax
on cmax.task_id = c.task_id and cmax.maxc = c.created;
答案 1 :(得分:0)
SELECT T.*, C.*
FROM tasks T
JOIN Commentaries C
ON T.id = C. task_id
GROUP BY T.id
ORDER BY C.task_id ASC
LIMIT 1
答案 2 :(得分:0)
select * from task,com where task.id=com.task_id order by com.da desc limit 1;