CTE 问题(with..as 构造)

Issue with CTE (with..as construction)

我正在尝试通过在线练习学习 CTE 结构。

这里是查询的简化版本:

with mr as 
(
     select min(ram) 
     from pc
)
select model 
from pc 
where ram = mr 
  and speed = (select max(speed) from pc where ram = mr)

失败并出现错误:

No column name was specified for column 1 of 'mr'

我尝试通过为聚合列添加别名来解决问题

with mr as 
(
    select min(ram) as v 
    from pc
) 
select model 
from pc 
where ram = mr.v 
  and speed = (select max(speed) from pc where ram = mr.v)

现在失败了

The multi-part identifier "mr.v" could not be bound

那么为什么上面的查询会产生错误,以及 - 编写此类查询的正确方法是什么?

mr 不是列,而是类似 table 的查询,您必须这样引用它:

with mr as (select min(ram) minram from pc) 
select model from pc 
where ram=(select minram from mr) 
and speed=(select max(speed) from pc where ram = (select minram from mr))

如果你想要一个更短的查询,然后假设你想要一行,然后使用 order by 和某种形式的限制:

select pc.*
from pc
order by ram desc, speed asc
fetch first 1 row only;

解决此问题的另一种方法是将两个子查询都定义为 CTE。

with mr as (select min(ram) min_ram from pc),
     ms as (select max(speed) as max_speed from pc where ram = (select minram from mr))

select pc.model 
from pc
    left join mr on pc.ram = mr.min_ram
    left join ms on pc.speed = ms.max_speed