Mysql左连接一行

我有三张桌子

驱动程序

  driver_id | driver_name |driver_number
  ----------------------------------------
    1       | Driver 1   | 99999
    2       | Driver 2   | 88888

每个司机都有班次

  shift_id | start_time            | end_time            | driver_id 
   -----------------------------------------------------------------
    4        |2015-04-02 10:09:00    |(NULL)               | 1
    3        |2015-04-02 09:19:00    |(NULL)               | 2
    2        |2015-04-02 11:09:00    |2015-04-02 19:09:00  | 1
    1        |2015-04-02 10:09:00    |2015-04-02 20:09:00  | 2

在每次轮班期间,驾驶员可能会或可能不会多次出行

     trip_id | start_time            | end_time            | shift_id 
       -----------------------------------------------------------------
        12       |2015-04-02 10:09:00    |(NULL)               | 4
        11       |2015-04-02 09:19:00    |(NULL)               | 4
        10       |2015-04-02 11:09:00    |2015-04-02 19:09:00  | 3
        9        |2015-04-02 10:09:00    |2015-04-02 20:09:00  | 2
        8        |2015-04-02 10:09:00    |(NULL)               | 4
        7        |2015-04-02 09:19:00    |(NULL)               | 4
        6        |2015-04-02 11:09:00    |2015-04-02 19:09:00  | 3
        5        |2015-04-02 10:09:00    |2015-04-02 20:09:00  | 4
        4        |2015-04-02 10:09:00    |(NULL)               | 4
        3        |2015-04-02 09:19:00    |(NULL)               | 4
        2        |2015-04-02 11:09:00    |2015-04-02 19:09:00  | 2
        1        |2015-04-02 10:09:00    |2015-04-02 20:09:00  | 1

我想得到一个查询,其中我获得最近的最多行程以及驾驶员详细信息,在开放班次(结束时间为null).

我一直在尝试的一切都失败了.

我理解查询应该是这样的:

select * from
drivers 
inner join shifts on shifts.driver_id = drivers.driver_id
left join (some inner query on trips table) as trip 
on shifts.shift_id = trip.trip_id
where shifts.end_time is null;

请帮我查询一下.预期的结果是这样的:

driver_id | driver_name | shift_id | shift_start_time    | recent_trip_id | recent_trip_start_time
1         | Driver 1    | 4        | 2015-05-02 10:09:00 | 12             | 2015-04-02 10:09:00
2         | Driver 2    | 3        | 2015-05-02 11:09:00 | 10             |  2015-04-02 11:09:00

最佳答案 您可以使用变量来确定每个班次分区中的最近行程:

SELECT d.driver_id, d.driver_name, s.shift_id, s.start_time AS shift_start_time, 
       t.trip_id AS recent_trip_id, t.start_time AS recent_trip_start_time
FROM drivers AS d
INNER JOIN shifts AS s ON s.driver_id = d.driver_id
INNER JOIN (
    SELECT trip_id, start_time, 
           @row_number:= CASE WHEN @sid = shift_id THEN @row_number+1
                              ELSE 1
                         END AS row_number,
           @sid:=shift_id AS shift_id  
    FROM trips, (SELECT @sid:=0,@row_number:=0) as vars
    ORDER BY shift_id, trip_id DESC ) t ON t.shift_id = s.shift_id AND t.row_number = 1
WHERE s.end_time IS NULL

谓词t.row_number = 1有效地选择每班最近的行程.查询的其余部分只是简单的JOIN子句,它们将驱动程序和(打开)移位数据聚集在一起.

SQL Fiddle Demo

点赞