选择1到n比较Mysql中每个的第二行

时间:2017-02-08 15:25:08

标签: mysql

我想提取他们的反向创建顺序的倒数第二位患者在2016年创建的医生

医师

| id |  name  |
|  1 |  Ryan  |
|  2 |  Pete  |
|  3 |  Anna  |
|  4 |  Harry |

患者

| id |  name  | surgeon_id | created_at |
|  1 | Gloria |     1      | 2016-05-01 |
|  2 | Bob    |     1      | 2016-06-21 |
|  3 | Alex   |     2      | 2015-05-01 |
|  4 | Jim    |     2      | 2016-05-01 |
|  3 | Kay    |     3      | 2016-05-01 |
|  5 | Kim    |     4      | 2016-05-01 |
|  6 | Joe    |     4      | 2017-01-03 |

因此结果必须是Ryan(1)和Harry(4):

|  1 | Gloria |     1      | 2016-05-01 |
|  5 | Kim    |     4      | 2016-05-01 |

1 个答案:

答案 0 :(得分:3)

<强> DEMO

首先,您使用变量为每位患者分配一个位置。

SELECT `id`, `name`, `surgeon_id`, `created_at`,
       @pos := IF(@surgeon_id = surgeon_id, 
                  @pos + 1, 
                  IF(@surgeon_id := surgeon_id, 1, 1) 
                 ) as rn
FROM Table1
CROSS JOIN (SELECT @pos := 0, @surgeon_id :=0 ) as parameters
ORDER BY `surgeon_id`, `created_at` DESC

然后使用它作为子查询来获得倒数第二个患者并测试一年。

SELECT `id`, `name`, `surgeon_id`, `created_at`
FROM (
        SELECT `id`, `name`, `surgeon_id`, `created_at`,
               @pos := IF(@surgeon_id = surgeon_id, 
                          @pos + 1, 
                          IF(@surgeon_id := surgeon_id, 1, 1) 
                         ) as rn
        FROM Table1
        CROSS JOIN (SELECT @pos := 0, @surgeon_id :=0 ) as parameters
        ORDER BY `surgeon_id`, `created_at` DESC
     ) T
WHERE T.rn = 2
  AND YEAR(`created_at`) = 2016

最后加入医生获取名称

SELECT Doctors.`id`, Doctors.`name`
FROM (
        SELECT `id`, `name`, `surgeon_id`, `created_at`,
               @pos := IF(@surgeon_id = surgeon_id, 
                          @pos + 1, 
                          IF(@surgeon_id := surgeon_id, 1, 1) 
                         ) as rn
        FROM Patients
        CROSS JOIN (SELECT @pos := 0, @surgeon_id :=0 ) as parameters
        ORDER BY `surgeon_id`, `created_at` DESC
     ) T
JOIN Doctors
  ON T.`surgeon_id` = Doctors.`id`
WHERE T.rn = 2
  AND YEAR(`created_at`) = 2016; 

<强> OUPUT:

enter image description here