程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> sql查詢-求幫忙優化我這條sql語句

sql查詢-求幫忙優化我這條sql語句

編輯:編程綜合問答
求幫忙優化我這條sql語句

首先說一下下面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
這兩個字段要加上索引,否則查詢很慢的。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved