This question already has answers here:
Retrieving the last record in each group - MySQL
(25个答案)
GROUP BY characteristic in mysql [closed]
(1个答案)
5年前关闭。
我在使用链接表和检索上次使用的值时遇到问题。
链接表:
link_devices_user

id | deviceId |  shopId  |
 1 |   359    |    46    |
 2 |   1339   |    46    |
 3 |   1328   |    45    |
 4 |   882    |    46    |

system_devices

id    | carId   | registerId   | lastUsed            |
 359  |   350   |  regi1       | 2014-01-03 09:00:00 |
 1339 |   350   |  regi2       | 2013-01-03 09:00:00 |
 1328 |   160   |  regi3       | 2012-01-03 09:00:00 |
 882  |   150   |  regi4       | 2014-01-03 08:59:00 |

现在我需要从连接到shopId 46的系统设备中检索最新的唯一carId。
所以在这种情况下,结果应该是。
882  |   150   |  regi4       | 2014-01-03 08:59:00 |
359  |   350   |  regi1       | 2014-01-03 09:00:00 |

我现在有以下问题。这给了我唯一的龋齿,但不是最新的唯一龋齿。我该换什么?
SELECT system_devices.id,
       carId,
FROM   link_devices_user
       INNER JOIN system_devices
               ON link_devices_user.deviceId = system_devices.id
WHERE  link_devices_user.shopid = '46'
GROUP  BY system_devices.carId
ORDER  BY system_devices.lastUsed DESC

最佳答案

试试这个:

SELECT s.*
FROM system_devices s LEFT JOIN system_devices s1
   ON (s.carId = s1.carId AND s.lastUsed < s1.lastUsed)
   INNER JOIN link_devices_user ld ON s.id = ld.deviceId
WHERE (s1.id IS NULL) AND (ld.shopId = 46)
ORDER BY carId

http://sqlfiddle.com/#!2/158d9/4
您可以检查提供所需结果的SQL fiddle示例。

08-03 14:42