改进SQL语句

时间:2016-08-23 06:03:11

标签: sql performance select join

我使用以下SQL语句来查询数据库:

SELECT
 ID, Date1, Date2, Value
FROM
 data t1
WHERE
 t1.ID = 100 AND Date2 BETWEEN '2010-01-01 00:00:00.0' AND '2010-01-31 23:59:59.0' AND t1.Date1 =
 (
  SELECT
   max(t2.Date1)
  FROM
   data t2
  WHERE
   t2.Date1 <= '2010-02-01 00:00:00.0' AND t2.ID = t1.ID AND t2.Date2 = t1.Date2
 ) 
ORDER BY
 t1.Date2

我正在使用SELECT语句。有没有更好的方法来改进SQL语句,或者使用JOIN

使其更快

感谢。

3 个答案:

答案 0 :(得分:0)

以下是使用cte和JOIN的方法。

;WITH cte_MaxDate
 AS  (
      SELECT  t2.ID,t2.Date2,MAX(t2.Date1) Maxdate1
      FROM data t2
      WHERE  t2.Date1 <= '2010-02-01 00:00:00.0' 
      GROUP BY t2.ID,t2.Date2
      ) 
SELECT  t1.ID, Date1, t1.Date2, Value
FROM  data t1
 JOIN cte_MaxDate m ON   t1.Date1 =m.Maxdate1 AND m.ID = t1.ID AND m.Date2 = t1.Date2
WHERE t1.ID = 100 AND t1.Date2 BETWEEN '2010-01-01 00:00:00.0' AND '2010-01-31 23:59:59.0' 

答案 1 :(得分:0)

您可以像这样使用

SELECT
 ID, Date1, Date2, Value
FROM
 data t1
join  (
  SELECT
   max(t2.Date1) as tDate
  FROM
   data t2
  WHERE
   t2.Date1 <= '2010-02-01 00:00:00.0' AND t2.ID = t1.ID AND t2.Date2 = t1.Date2
 ) A on t1.Date1 =A.tDate
WHERE
 t1.ID = 100 AND Date2 BETWEEN '2010-01-01 00:00:00.0' AND '2010-01-31 23:59:59.0' 
ORDER BY
 t1.Date2

答案 2 :(得分:0)

首先,我建议不要使用CTE请查找以下链接查看我这样说的原因

https://dba.stackexchange.com/questions/13112/whats-the-difference-between-a-cte-and-a-temp-table

现在你可以使用这个

SELECT  t2.ID,t2.Date2,MAX(t2.Date1) Maxdate1 into #Temp 
  FROM data t2
  WHERE  t2.Date1 <= '2010-02-01 00:00:00.0' 
  GROUP BY t2.ID,t2.Date2

现在使用

在临时表上创建索引
Create Index T on #Temp (ID,Date2,Maxdate1)

不使用此

SELECT  t1.ID, Date1, t1.Date2, Value
FROM  data t1
  JOIN #Temp m ON   t1.Date1 =m.Maxdate1 AND m.ID = t1.ID AND  m.Date2 = t1.Date2
 WHERE t1.ID = 100 AND t1.Date2 BETWEEN '2010-01-01 00:00:00.0' AND '2010-01-31 23:59:59.0' 

请回复