仅从具有where条件的连接表中选择第一条记录

时间:2015-07-20 14:45:20

标签: mysql sql codeigniter

我使用PHP解决了这个问题,但我知道如果我可以为它做一个查询会更快。我有以下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 |
+------------+------------+-------------+---------------------+

我需要一个查询,它将选择状态为1或2的相关任务的所有项目。它选择的任务必须是最新的。见下表。

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                |
+------------+--------------+------------+-------------+---------------------+

正如您所见,项目2不应该有任务,因为任务状态是2.而项目4没有项目。项目1有2个任务,但最早的任务早一天。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用状态为12的最新任务进行左连接。查询会像这样:

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

Live demo

答案 1 :(得分:-3)

你可以试试这个: -

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