Mysql query from multiple tables
Posted: Sun Apr 12, 2009 10:45 am
I have several temperature sensors mounted in my house and I am trying to list the last known measurement for every sensor on a webpage.
Getting the right data from the database is a tough one, so maybe someone is able to help me out.
I have three tables:There is a one-to-many relation between the tables <i><b>Devices</b></i> and <i><b>DeviceDataOregonTempHum</b></i> and a one-on-one relation between <i><b>Devices</b></i> and <i><b>DeviceLocation</b></i>. For every sensor in table <i><b>Devices</b></i> I need the last entry from table <i><b>DeviceDataOregonTempHum</b></i> and the corresponding location from table <i><b>DeviceLocation</b></i>.
The following query nearly does what it needs to do. However: For every device in table <i>Devices</i> it displays all records from table <i>DeviceData</i> instead of only the last entry:The output looks something like this:Adding a 'GROUP BY t1.Id' to the query nearly gives me the output I need, only it displays every FIRST record from table <i><b>DeviceDataOregonTempHum</b></i> instead of the last one and I have not been able yet to make it display the LAST record. I tried various GROUP BY and ORDER BY versions of the query, changed the order of the tables in the query, but still no luck.
Is there anyone out there who knows the solution?
Getting the right data from the database is a tough one, so maybe someone is able to help me out.
I have three tables:
Code: Select all
Devices DeviceDataOregonTempHum
- Id ---------> - DevId
- DevType | - DevTemp
| - DevHum
| - DevUpd
|
| DeviceLocation
|-> - Id
- Description
The following query nearly does what it needs to do. However: For every device in table <i>Devices</i> it displays all records from table <i>DeviceData</i> instead of only the last entry:
Code: Select all
SELECT t1.Id, t2.DevTemp, t2.DevHum, t2.DevUpd, t3.DevLoc
FROM Devices AS t1
JOIN DeviceDataOregonTempHum AS t2
ON (t2.DevId = t1.Id)
JOIN DeviceLocation AS t3
ON (t3.Id = t1.DevLoc)
WHERE (t1.DevType = '1');
Code: Select all
| 39 | 19.4 | 55 | 2009-04-12 08:00:06 | Werkkamer |
| 39 | 19.4 | 55 | 2009-04-12 09:00:06 | Werkkamer |
| 39 | 19.9 | 57 | 2009-04-12 10:00:05 | Werkkamer |
+----+---------+--------+---------------------+-----------------+
1329 rows in set (0.00 sec)
Is there anyone out there who knows the solution?