首先說一下下面sql語句要用到的表的基本情況:
一、有三張表,一張叫equipment,一張叫sensor,一張叫sensorInputData
二、三表關系是equipment下有多個sensor,sensor下有多個sensorInputdata,所以sensor下有一個equipment的主鍵quipmentId做外鍵,sensorInputData下也有一個sensor的主鍵sensorId做外鍵,其他都是各自表的屬性,應該能比較清晰的看出來
下面是我的查詢代碼:
select
equipment.equipmentName as 設備,
equipment.longitude as 經度,
equipment.latitude as 緯度,
equipment.equipmentType as 設備類型,
data.數據類型 as 數據類型,
Convert(decimal(18,2),data.數據) as 數據,
data.單位 as 單位,
convert(varchar(20), data.日期,120) as 日期
from EquipmentMessage as equipment
left join
(
select
sensor.sensorUnit as 單位,
sensorData.value as 數據,
sensorData.date as 日期,
sensorData.valueType as 數據類型,
sensor.equipmentId as equipmentId
from Sensor as sensor
join SensorInputData as sensorData on sensor.sensorId=sensorData.sensorId
and not exists
(
select 1 from SensorInputData as t where t.sensorId=sensorData.sensorId and t.date>sensorData.date
)
) as data on equipment.equipmentId=data.equipmentId
左連接是查出傳感器(sensor表)與傳感器的第一條數據(sensorInputData表)
t.sensorId=sensorData.sensorId and t.date>sensorData.date
這兩個字段要加上索引,否則查詢很慢的。