0

我的表描述是

+-------------+-----------------+------+-----+-------------------+-----------------------------+
| Field       | Type            | Null | Key | Default           | Extra                       |
+-------------+-----------------+------+-----+-------------------+-----------------------------+
| AutoPk      | int(4) unsigned | NO   | MUL | NULL              |                             |
| sensorName  | varchar(20)     | NO   |     | NULL              |                             |
| SensorValue | double(65,2)    | NO   |     | 0.00              |                             |
| timest      | timestamp       | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+-----------------+------+-----+-------------------+-----------------------------+

Sample data is 

+----------+--------------+--------------+---------------------+
| AutoPk8_ | sensorName8_ | SensorVa3_8_ | timest8_            |
+----------+--------------+--------------+---------------------+
|      104 | temperature  |        14.22 | 2013-09-20 09:59:35 |
|      104 | humidity     |        71.74 | 2013-09-20 09:59:35 |
|      104 | humidity     |        71.24 | 2013-09-20 09:56:42 |
|      104 | temperature  |        14.36 | 2013-09-20 09:56:41 |
|      104 | temperature  |        14.47 | 2013-09-20 09:53:47 |
|      104 | humidity     |        71.03 | 2013-09-20 09:53:47 |
|      104 | temperature  |        14.74 | 2013-09-20 09:50:54 |
|      104 | humidity     |        70.50 | 2013-09-20 09:50:54 |
|      104 | light intensi|        12    | 2013-09-20 09:49:00 |       
|      104 | temperature  |        15.28 | 2013-09-20 09:48:00 |
|      104 | humidity     |        69.60 | 2013-09-20 09:48:00 |
+----------+--------------+--------------+---------------------+
10 rows in set (0.06 sec)

现在我需要一个查询来查找基于 sensorName 的最新记录。这里的最新记录是指最新的时间记录。

对于上面的 i/p 输出应该是

 104 | temperature  |        14.22 | 2013-09-20 09:59:35
 104 | humidity     |        71.74 | 2013-09-20 09:59:35 
 104 | light intensi|        12    | 2013-09-20 09:49:00 

请帮我 。提前致谢。

4

2 回答 2

2

简单地,

SELECT
  MyTable.AutoPk,MyTable.sensorName,MyTable.SensorValue,MyTable.SensorValue,MyTable.timest
FROM (SELECT
  MAX(timest8_) AS RegTime,
  sensorName8_
FROM MyTable
GROUP BY sensorName8_)
AS Result1
INNER JOIN MyTable
  ON Result1.RegTime = MyTable.timest8_
WHERE Result1.sensorName8_ = MyTable.sensorName8_

选择最新的 timest8_ 及其传感器名称,然后将结果集与 MyTable 进行内部连接。从结果集中可以选择所需的列。

于 2013-09-20T04:57:06.833 回答
0

我找不到表名,所以假设它的表名,并命名您要查找的表名,这应该返回具有该名称的最新记录。

SELECT * FROM TableName WHERE sensorName = 'Name' ORDER BY timest DESC LIMIT 1 
于 2013-09-20T04:58:34.763 回答