检索最新的mysql条目

时间:2014-01-21 22:39:39

标签: mysql

我有一个项目表和一个任务表。我想检索一个项目列表,然后为每个项目显示最新的due_date任务。

下面的代码用于显示项目并将检索一个任务,但它似乎不会使用最新的due_date检索任务,而是似乎检索具有最低id主键的任务。如果我允许多个任务显示结果按due_date排序,但我想将它们限制为一个。

SELECT t.*, p.id as project_id, p.name as project_name, p.archive as project_archive
FROM project p
JOIN user_project up ON p.id = up.project AND up.user = '.$user.'
 LEFT JOIN (SELECT tmp.* FROM
(SELECT *, IF( @prev <> project_id, @rownum := 1, @rownum := @rownum+1 ) AS rank, @prev := project_id
FROM task t
JOIN (SELECT @rownum := NULL, @prev := 0) AS r 
WHERE user_id = '.$user.' 
ORDER BY t.project_id) AS tmp
WHERE tmp.rank <= 1) AS t ON p.id = t.project_id
ORDER BY p.id asc, t.due_date desc

3 个答案:

答案 0 :(得分:1)

此查询可以帮助您

SELECT *
FROM project p
JOIN user_project up ON p.id = up.project AND up.user = '.$user.'
left join task on p.id = task.project_id and 
task.due_date = (select max(due_date) from task where project_id = p.id)

答案 1 :(得分:1)

$ SELECT * 来自项目p JO_ user_project up on p.id = up.project AND up.user ='。$ user。' 在p.id = task.project_id和。左连接任务 task.due_date =(从任务中选择max(due_date),其中project_id = p.id)$

答案 2 :(得分:0)

感谢所有试图提供帮助的人。我最终通过更改行

解决了这个问题
ORDER BY t.project_id) AS tmp

ORDER BY t.project_id, t.due_date desc) AS tmp