1

我有这样的 SELECT 语句:

SELECT 
T1.COD,
T1.NAME, 
(SELECT MAX(T2.DATA)
  FROM dbo.TAB2 T2
  WHERE T2.COD = T1.COD) AS ENDDATA
FROM dbo.TAB1 AS T1 WITH (NOLOCK) 

有没有使用 SUBQUERY 的替代方法?可以使用JOIN吗?

我必须找到一个更有效的解决方案来运行这个查询。

非常感谢你。

4

4 回答 4

2

要返回与原始查询相同的结果,您需要以下内容:

SELECT T1.COD, T1.NAME, s.ENDDATA
FROM dbo.TAB1 T1 WITH (NOLOCK)  left outer join
     (SELECT t2.cod, MAX(T2.DATA) as EndData
      FROM dbo.TAB2 T2
      group by T2.COD
     ) s
     on t1.cod = s.cod

在连接之外进行分组会改变查询的语义。特别是,您将只返回每个 COD/NAME 的一行,即使 T1 中可能存在重复。这可能是可取的。但是,您的原始查询会有重复项。

另外,为什么您在 TAB1 上有 NOLOCK 而在 TAB2 上没有?

于 2012-06-27T16:45:26.150 回答
0

是的,您可以使用 JOIN:

SELECT 
   T1.COD,
   T1.NAME, 
   MAX(T2.DATA) AS ENDDATA
FROM dbo.TAB1 AS T1 WITH (NOLOCK) 
JOIN dbo.TAB2 T2 WITH (NOLOCK) -- Assumed
  ON T2.COD = T1.COD
GROUP BY
   T1.COD,
   T1.NAME
于 2012-06-27T16:20:53.053 回答
0
SELECT   T1.COD,
         T1.NAME, 
         MAX(T2.DATA)
FROM     TAB1 AS T1
JOIN     TAB2 AS T2
ON       T2.COD = T1.COD
GROUP BY T1.COD,
         T1.NAME;
于 2012-06-27T16:21:14.123 回答
0

Why you don't want to use subselect? You can replace it with outer apply statement (which looks better from my point of view) but in the most cases you will get the same execution plan. Yes, actually it depends on your indexes (I assume that you have index on COD in TAB2 table) and data (I assume that row count in both table is more or less big and row count in TAB2 is definitely bigger than row count in TAB1).

Solution with grouping by COD and NAME is the worst solution. Solution with subquery is identical to outer apply. Solution with outer apply is more or less good solution (even better to use cross apply but in such case you should be sure that you don't have rows in TAB1 without associated rows in TAB1).

于 2012-06-27T17:04:48.957 回答