如何在SQL中避免重复的子查询JOIN?

时间:2010-03-25 13:44:39

标签: sql sql-server-2008 join subquery

在SQL Server 2008中:

我有一张桌子,我想按照以下几点做一些事情:

SELECT T1.stuff, T2.morestuff from
(
 SELECT code, date1, date2 from Table
) as T1
INNER JOIN
(
 SELECT code, date1, date2 from Table
) as T2

ON T1.code = T2.code and  T1.date1 = T2.date2

两个子查询完全相同。有没有办法在不重复子查询脚本的情况下做到这一点?

由于

卡尔

4 个答案:

答案 0 :(得分:7)

CTE:

;WITH YourQuery AS
(
 SELECT code, date1, date2 from Table
)
SELECT 
    T1.stuff, T2.morestuff 
    from YourQuery           T1
        INNER JOIN YourQuery T2 ON T1.code = T2.code and  T1.date1 = T2.date2

FYI

在问题中,代码使用派生表,也称为内联视图。子查询是一个SELECT查询,它返回单个值并嵌套在SELECT,INSERT,UPDATE或DELETE语句中,或嵌套在另一个子查询中。子查询可以在允许表达式的任何地方使用。请参阅:http://msdn.microsoft.com/en-us/library/aa213252(SQL.80).aspx

答案 1 :(得分:0)

您可以使用视图。

CREATE VIEW myView AS 
SELECT code, date1, date2 
FROM Table

然后您的查询将是这样的:

SELECT T1.stuff, T2.morestuff 
FROM myView as T1
INNER JOIN myView as T2 ON T1.code = T2.code and  T1.date1 = T2.date2

答案 2 :(得分:0)

他们为什么要进行子查询?

SELECT T1.stuff, T2.morestuff
FROM Table T1
INNER JOIN Table T2
ON T1.code = T2.code and T1.date1 = T2.date2

答案 3 :(得分:0)

为什么表格的两次别名不起作用?

SELECT T1.stuff, T2.stuff FROM Table as T1 INNER JOIN Table as T2
ON T1.code = T2.code and  T1.date1 = T2.date2