如何避免 SQL 中重复的子查询 JOIN?
在 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
两个子查询完全相同。有什么方法可以在不重复子查询脚本的情况下做到这一点?
谢谢卡尔
In SQL Server 2008:
I have one table, and I want to do something along the following lines:
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
The two subqueries are exactly identical. Is there any way I can do this without repeating the subquery script?
Thanks
Karl
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CTE:
仅供参考,
在问题中,代码使用派生表,也称为内联视图。子查询是返回单个值的 SELECT 查询,并且嵌套在 SELECT、INSERT、UPDATE 或 DELETE 语句内或另一个子查询内。子查询可以用在允许表达式的任何地方。请参阅:http://msdn.microsoft.com/en-我们/库/aa213252(SQL.80).aspx
CTE:
FYI
In the question, the code is using derived tables, also known as inline views. A subquery is a SELECT query that returns a single value and is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. A subquery can be used anywhere an expression is allowed. See: http://msdn.microsoft.com/en-us/library/aa213252(SQL.80).aspx
您可以使用视图。
然后你的查询将是这样的:
You can use a View.
And then your query would be something like this:
为什么它们是子查询?
Why are they subqueries at all?
为什么给表添加两次别名不起作用?
Why wouldn't aliasing the table twice work?