如何将排序依据和分组依据组合在一起?条件:按一列排序,按另一列排序

时间:2019-03-16 05:51:45

标签: mysql group-by sql-order-by

在MySQL中,按顺序和按组合分组存在一个问题。 以下是我的表结构。

+-------------+-----------+-----------+----------------------------+
| driver_id   | lat       | lng       | creation                   |
+-------------+-----------+-----------+----------------------------+
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-13 09:21:39.225873 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 12:30:09.608296 |
| TDRV-000021 | 18.659135 | 73.756445 | 2019-03-10 15:38:37.954508 |

当我使用以下SQL命令(按创建顺序排序)时,

select driver_id, lat, lng, creation from `tabReal Time Location` order by creation desc;

我得到了以下结果,

+-------------+-----------+-----------+----------------------------+
| driver_id   | lat       | lng       | creation                   |
+-------------+-----------+-----------+----------------------------+
| TDRV-000021 | 20.659180 | 73.756480 | 2019-03-16 08:13:41.155528 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:44:06.206690 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:36:25.571260 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:35:55.115124 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:35:46.281953 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:35:00.986849 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:33:38.370099 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:32:57.589272 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:30:24.582391 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-15 19:29:23.809564 |

并且当我习惯组合订单和分组依据时,

select driver_id, lat, lng, creation from `tabReal Time Location` group by driver_id order by creation desc;

+-------------+-----------+-----------+----------------------------+
| driver_id   | lat       | lng       | creation                   |
+-------------+-----------+-----------+----------------------------+
| TDRV-000027 | 18.659180 | 73.756480 | 2019-03-15 13:47:37.338828 |
| TDRV-000021 | 18.659180 | 73.756480 | 2019-03-13 09:21:39.225873 |
+-------------+-----------+-----------+----------------------------+

但是正如您在上述结果中看到的那样,我得到了错误的结果,我期望下面的最新更新 lat,lng 列。

+-------------+-----------+-----------+----------------------------+
| driver_id   | lat       | lng       | creation                   |
+-------------+-----------+-----------+----------------------------+
| TDRV-000021 | 20.659180 | 73.756480 | 2019-03-16 08:13:41.155528 |
| TDRV-000027 | 20.659180 | 90.756480 | 2019-03-15 14:07:41.543089 |
+-------------+-----------+-----------+----------------------------+

1 个答案:

答案 0 :(得分:1)

这是期待最新更新的消息的一种方法

select t.driver_id, lat, lng, order_id  from `tabReal Time Location` t INNER JOIN  (select max(creation) as latest_date,driver_id  FROM `tabReal Time Location` group by  driver_id)d ON t.creation= d.latest_date and d.driver_id = t.driver_id;