[英]Selecting first record only from join table with a where condition
I have worked this problem out using PHP but I know it will be faster if I could make one query for it. 我已经使用PHP解决了这个问题,但是我知道如果可以对其进行查询,它将更快。 I have the following 2 tables. 我有以下2表。
projects:
+------------+--------------+
| project_id | project_name |
+------------+--------------+
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
+------------+--------------+
tasks:
+------------+------------+-------------+---------------------+
| project_id | task_id | task_status | task_due_timestamp |
+------------+------------+-------------+---------------------+
| 1 | 1 | 1 | 2015-01-01 12:00:00 |
| 1 | 2 | 2 | 2015-01-02 12:00:00 |
| 2 | 3 | 3 | 2015-01-03 12:00:00 |
| 3 | 4 | 1 | 2015-01-04 12:00:00 |
+------------+------------+-------------+---------------------+
I need a query that will select ALL projects with their associated task that has a status of 1 OR 2. And the task it selects has to be the most recent one. 我需要一个查询,该查询将选择状态为1或2的所有项目及其关联的任务,并且它选择的任务必须是最新的。 See the below table. 请参阅下表。
records after query:
+------------+--------------+------------+-------------+---------------------+
| project_id | project_name | task_id | task_status | task_due_timestamp |
+------------+--------------+------------+-------------+---------------------+
| 1 | a | 1 | 1 | 2015-01-01 12:00:00 |
| 2 | b | null | null | null |
| 3 | c | 3 | 3 | 2015-01-01 12:00:00 |
| 4 | d | null | null | null |
+------------+--------------+------------+-------------+---------------------+
As you can see project 2 shouldn't have a task as the task status is 2. And project 4 has no projects. 如您所见,项目2不应该包含任务,因为任务状态为2。项目4没有项目。 Project 1 has 2 tasks but the earliest one is earlier by a day. 项目1有2个任务,但最早的任务要早一天。
Any help would be greatly appreciated. 任何帮助将不胜感激。
You can try with a left join on the most recent tasks with status 1
or 2
. 您可以尝试左联接执行状态为1
或2
最新任务。 The query would like something like this: 该查询将如下所示:
select p.*, t.*
from projects as p
left join (
select t1.*
from tasks as t1
where t1.task_status in (1, 2)
and not exists (
select task_id from tasks as t2
where t1.task_id <> t2.task_id
and t1.project_id = t2.project_id
and t2.task_status in (1, 2)
and t2.task_due_timestamp > t1.task_due_timestamp
)
) as t on p.project_id = t.project_id
You can try this:- 您可以尝试以下方法:
SELECT P.project_id, P.project_name, T.task_id, T.task_status, MIN(T.task_due_timestamp)
FROM projects P INNER JOIN tasks T
ON P.project_id = T.project_id
AND T.task_status IN (1,2)
GROUP BY P.project_id, P.project_name, T.task_id, T.task_status
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.