将表连接到自身时出错

时间:2017-05-24 11:07:11

标签: mysql

我有一张表格,其中存储了测量温度和湿度的数据。带温度的记录将字段meas_kind设置为" T",对于湿度,将其设置为" H"。

mysql> describe meteo;
+-----------+---------------------+------+-----+---------+----------------+
| Field     | Type                | Null | Key | Default | Extra          |
+-----------+---------------------+------+-----+---------+----------------+
| id        | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| meas_time | timestamp           | YES  |     | NULL    |                |
| room      | varchar(10)         | NO   |     | NULL    |                |
| meas_kind | char(1)             | NO   |     | NULL    |                |
| value     | double              | NO   |     | NULL    |                |
+-----------+---------------------+------+-----+---------+----------------+

mysql> select * from meteo;
+----+---------------------+------+-----------+-------+
| id | meas_time           | room | meas_kind | value |
+----+---------------------+------+-----------+-------+
| 35 | 2017-05-24 16:51:47 | 123  | T         | 22.61 |
| 36 | 2017-05-24 16:51:47 | 123  | H         | 36.93 |
| 37 | 2017-05-24 16:51:51 | 123  | T         | 22.61 |
| 38 | 2017-05-24 16:51:51 | 123  | H         | 36.94 |
| 39 | 2017-05-24 16:51:56 | 123  | T         | 22.61 |
| 40 | 2017-05-24 16:51:56 | 123  | H         | 36.94 |
+----+---------------------+------+-----------+-------+

同时测量温度和湿度,所以我希望这个表格如下:

+---------------------+------+-------+-------+
| meas_time           | room | Temp  | Humid |
+---------------------+------+-------+-------+
| 2017-05-24 16:51:47 | 123  | 22.61 | 36.93 |
| 2017-05-24 16:51:51 | 123  | 22.61 | 36.94 |
| 2017-05-24 16:51:56 | 123  | 22.61 | 36.94 |
+---------------------+------+-------+-------+

我已尝试进行此查询,但它给了我一个错误:

  

错误1242(21000):子查询返回超过1行

请帮助我获得正确的结果。

select 
    m.meas_time, 
    m.room, 
    (select value from meteo m1 where m1.meas_kind='T' and m.meas_time=m1.meas_time) as Temp, 
    (select value from meteo m2 where meas_kind='H' and m.meas_time=m2.meas_time) as Humid 
from meteo m 
     join meteo m1 
         on m.meas_time=m1.meas_time 
         and m.room=m1.room 
     join meteo m2 
         on m.meas_time=m2.meas_time 
         and m.room=m2.room 
group by m.room, m.meas_time;

1 个答案:

答案 0 :(得分:1)

你太复杂了。简单的数据透视查询可以为您提供所需的结果。

SELECT
    meas_time,
    room,
    MAX(CASE WHEN meas_kind = 'T' THEN value END) AS Temp,
    MAX(CASE WHEN meas_kind = 'H' THEN value END) AS Humid
FROM meteo
GROUP BY meas_time, room