涉及两个表的SQL语句

时间:2015-08-26 16:24:03

标签: python mysql

我有两个表,传感器和sensor_desc。我想从最后插入sensor_id的两个表中检索sensor.date和sensor_desc.location。

我已尝试过这段无效的代码。

        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

2 个答案:

答案 0 :(得分: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 :(得分: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