保存 SQL 查询的中间结果

Save the intermediate result of SQL query

我想知道是否有任何方法可以将中间结果或 tables 保存在 SQL 中。例如,假设您有两个不同的 SQL 语句,在第一个语句中您连接了两个 table,然后您想查看结果 table 有多少行。我知道有很多方法可以做到这一点,但我很想知道如何按顺序完成。考虑以下示例:

select * from order_table left join customer_table on order_table.id = customer_table.id

然后我想查看行数(举个简单的例子)

select count(*) from table 

但我不知道这个 table 应该是什么。我如何将上述查询的结果保存在某些逻辑 table 中或如何引用之前在 SQL.

中创建的内容

对于这个特定的示例,您可以简单地将原始查询包装在 sub-query:

select count(*)
from (
    select *
    from order_table
    left join customer_table on order_table.id = customer_table.id
) as x

如果您想要存储结果到物理table(临时或永久)中,那么每个 rdbms 的过程会有所不同。例如,在 SQL 服务器中,您将使用 SELECT INTO:

select * 
into #temp_table
from order_table
left join customer_table on order_table.id = customer_table.id

您可以像下面这样使用 WITH:

WITH resultTable as ( select * from order_table left join customer_table on order_table.id = customer_table.id )

select count(*) from resultTable

你也可以使用 CTE。对于您的问题,它将是:

;
with table1 as (
select * from order_table 
left join customer_table on order_table.id = customer_table.id
)
select count(*) from table1
GO