我的表格描述是
+-------------+-----------------+------+-----+-------------------+-----------------------------+
| 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
请帮帮我。提前致谢。
答案 0 :(得分: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。从结果集中可以选择所需的列。
答案 1 :(得分:0)
我找不到tablename,所以假设它的TableName,并命名你要查找的那个,这应该返回带有该名称的最新记录。
SELECT * FROM TableName WHERE sensorName = 'Name' ORDER BY timest DESC LIMIT 1