2015-08-26 81 views
0

我有两个表,sensor和sensor_desc。我想从上次插入sensor_id的两个表中检索sensor.date和sensor_desc.location。涉及两个表的SQL语句

我试过这段代码不起作用。

 cur = con.cursor() 
     cur.execute("Select sensor_id from sensor order by date desc limit 1") 
     con.commit() 
     last= cur.fetchall() 
     print '%s' %last 
     cur1= con.cursor() 
     cur.execute("Select sensor.date, sensor_desc.location from sensor, sensor_desc where sensor.sensor_id= %s AND sensor_desc.sensor_id=%s",(last, last)) 
     con.commit() 
     lastseen = cur1.fetchall() 
     print '%s'%lastseen 

传感器

+-----------+---------------------+-------+ 
| sensor_id | date    | value | 
+-----------+---------------------+-------+ 
| 12345  | 2015-08-17 10:16:41 | NULL | 
| 12345  | 2015-08-17 10:17:29 | NULL | 
| 12345  | 2015-08-17 10:18:06 | NULL | 
| 12345  | 2015-08-17 13:28:55 | 1 | 
| 12345  | 2015-08-17 13:29:49 | 1 | 
+-----------+---------------------+-------+ 

sensor_desc

+-----------+--------------------+-------------+ 
| sensor_id | description  | location | 
+-----------+--------------------+-------------+ 
| 12341  | Motion Sensor  | Kitchen  | 
| 12342  | Motion Sensor  | Toilet  | 
| 12343  | Motion Sensor  | Living Room | 
| 12344  | Motion Sensor  | BedRoom  | 
| 12345  | Panic Button  | NULL  | 
| 12346  | Temperature Sensor | NULL  | 
| 12347  | CO2 Sensor   | NULL  | 
+-----------+--------------------+-------------+ 

Here is the fiddle

+0

它是如何工作的?你期望结果如何?你现在得到什么结果?请编辑问题并添加此信息。 –

+1

请标记您正在使用的语言。我现在的想法是,您需要将两个表加入到一起,按照降序排列的sensor_id的ORDER BY,然后限制为一条记录。 –

+0

@Tyra,请停止删除您的其他问题。我正在准备一个关于在数据库表中存储XBee地址的问题的答案,但是在我提交之前将其删除(两次!)。 – tomlogic

回答

2

我认为你结合两个查询得到这个:

select sensor.date, sensor_desc.location 
from sensor, sensor_desc 
where sensor.sensor_id = sensor_desc.sensor_id 
order by sensor.date desc 
limit 1 

很多人在这里会更喜欢你使用inner join的语法,但我想强调你已经有多接近某些工作。

1

您应该运行的SQL语句应该在两个表之间连接,按日期排序,然后只抓取第一条记录。

我在这里使用INNER JOIN只是因为你可以这样省略WHERE子句(我觉得它更具可读性)。

SELECT sensor.date, sensor_desc.location 
FROM sensor 
    INNER JOIN sensor_desc ON sensor.sensor_id = sensor_desc.sensor_id 
ORDER BY sensor.date DESC 
LIMIT 1