在第三个表中连接两个表数据

时间:2014-02-21 08:55:49

标签: mysql

我有两个表,一个是sensor_info,另一个是bays_info.here是表

id  Sensor_Name   stn_id    value  Station_id
1   Sensor1          0       4.4      1
2   Sensor2          0       2.1      1
3   Sensor3          0       3.2      1
4   Sensor4          1       4.5      1 

Bays_info

gate_id     bay_name    bay_status    Station_id  

GATE1       B_gate1         1            1
GATE2       B_gate2        -999          1
GATE3       B_gate2         1            1
GATE4       B_gate2        -999          1
GATE5       B_gate2          1           1

朋友我需要为每个门显示所有“传感器值”,如下所示(此处站点ID为常用列)

gate_id     bay_name    bay_status    Station_id  Sensor1  Sensor2 sensor3 sensor4

GATE1       B_gate1         1            1         4.4       2.1    3.2      4.5
GATE2       B_gate2        -999          1         4.4       2.1    3.2      4.5
GATE3       B_gate2         1            1         4.4       2.1    3.2      4.5
GATE4       B_gate2        -999          1         4.4       2.1    3.2      4.5
GATE5       B_gate2          1           1         4.4       2.1    3.2      4.5

所以我需要为传感器表显示每个站的值,还需要将传感器名称显示为header.Please帮我查询MySQL。

1 个答案:

答案 0 :(得分:1)

试试这个

   select gate_id  ,   bay_name ,   bay_status  ,  bays_info.Station_id,
   max(case when Sensor_Name = 'US.SEN1' then round(value,2) end) as Sensor1,
   max(case when Sensor_Name = 'US.SEN2' then round(value,2) end) as Sensor2,
   max(case when Sensor_Name = 'US.SEN3' then round(value,2) end) as Sensor3,
   max(case when Sensor_Name = 'DS.SEN1' then round(value,2) end) as Sensor4,
   max(case when Sensor_Name = 'DS.SEN2' then round(value,2) end) as Sensor5,
   max(case when Sensor_Name = 'DS.SEN3' then round(value,2) end) as Sensor6,
   max(case when Sensor_Name = 'MS.SEN1' then round(value,2) end) as Sensor7
   from bays_info
   inner join sensor_info 
   on sensor_info.Station_id = bays_info.Station_id
   group by gate_id

DEMO HERE