最新组由MYSQL +链表

时间:2014-01-03 09:37:46

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

我遇到了链接表和检索lastUsed值的问题。

链接表:

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的system_devices中检索最新的唯一carId。 所以在这种情况下,结果应该是。

882  |   150   |  regi4       | 2014-01-03 08:59:00 |
359  |   350   |  regi1       | 2014-01-03 09:00:00 |

我现在有以下查询。这给了我独特的carId但不是最新的独特carId。我应该改变什么?

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 

2 个答案:

答案 0 :(得分:1)

试试这个:

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小提琴样本。

答案 1 :(得分:0)

试试这个:

SELECT A.id, A.carId, A.registerId, A.lastUsed 
FROM (SELECT sd.id, sd.carId, sd.registerId, sd.lastUsed 
      FROM system_devices sd
      INNER JOIN link_devices_user ld ON sd.id = ld.deviceId
      WHERE ld.shopId = 46
      ORDER BY sd.id, sd.carId DESC
     ) AS A 
GROUP BY A.id

SELECT sd.id, sd.carId, sd.registerId, sd.lastUsed 
FROM system_devices sd
INNER JOIN link_devices_user ld ON sd.id = ld.deviceId
INNER JOIN (SELECT id, MAX(carId) carId FROM system_devices GROUP BY id) A ON A.id = sd.id AND A.carId = sd.carId 
WHERE ld.shopId = 46
ORDER BY sd.id