如何结合WHERE子句使用WITH子句

时间:2017-07-27 08:52:26

标签: sql postgresql common-table-expression

我收到了以下未运行的查询:

with countf as (
    select nationid, count(*) as c from customer
    group by nationid
),
maxf as ( select max(nationid) from customer )

select c.customerid, c.nationid from customer c, countf cf, maxf m
where c.nationid = cf.nationid
and cf.c = m

问题似乎是m是记录而不是整数。但是,如果我将其作为子查询运行,如下所示:

cf.c = ( select max(nationid) from customer )

它按预期工作。我认为我使用with语句并不是预期的方式。试图

cf.c in maxf

让我假设使用WITH生成的表不应该在WHERE子句中使用。

我知道还有其他方法可以使用all来获取相同的查询。我真的只对我应该如何使用with语句感兴趣。我以后只能将它用于SELECT吗?

提前感谢您提供任何帮助。

2 个答案:

答案 0 :(得分:1)

因为条件and cf.c = m应该如下所示

with countf as (
    select nationid, count(*) as c from customer
    group by nationid
),
maxf as ( select max(nationid) as max_nationid from customer )

select c.customerid, c.nationid from customer c, countf cf, maxf m
where c.nationid = cf.nationid
and cf.c = m.max_nationid

旁注:使用适当的ANSI样式JOIN语法,这种语法更像

select c.customerid, 
c.nationid from customer c
join  countf cf on c.nationid = cf.nationid
join maxf m on cf.c = m.max_nationid

答案 1 :(得分:0)

使用记录语法:

and row(cf.c) = m