我有一张包含" work"对于给定的"项目"我希望从每个项目的表中获得下一行。
TABLE project { id, name }
TABLE work {id, project_id, value, done}
在一次完成新工作之前,正确,高效的查询是什么?以下查询不起作用,并将选择列替换为min(columnhere)
会导致多行不匹配的结果。
SELECT w.id, p.name, w.value FROM work w
LEFT JOIN project p ON p.id = w.project_id
GROUP BY project_id
上述查询的结果应如下所示:
34, "Project 1", "Work 43", "..."
21, "Project 2", "Work 10", "..."
321, "Project 3", "Work 86", "..."
答案 0 :(得分:1)
如果我正确地阅读了您的问题,并且您每个项目需要一次(尚未完成)工作,那么正在寻找类似的东西
SELECT n.id, n.project_id, p.name project, w.value work
FROM
(
SELECT project_id, MIN(id) id
FROM work
WHERE done = 0
GROUP BY project_id
) n JOIN work w
ON n.id = w.id JOIN project p
ON n.project_id = p.id
说明:
work
以获取基于ID projects
以获取项目名称
样本输出:+------+------------+-----------+---------+ | id | project_id | project | work | +------+------------+-----------+---------+ | 43 | 34 | Project 1 | Work 43 | | 10 | 21 | Project 2 | Work 10 | | 86 | 321 | Project 3 | Work 86 | +------+------------+-----------+---------+