2015-08-26 124 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