[英]missing FROM-clause entry for table “g”
select distinct "BillingCountry", count(g."Name") as genre_occurance from
(select "BillingCountry", g."Name" as sub2 from "Invoice"
join "InvoiceLine" as invl on invl."InvoiceId" = "Invoice"."InvoiceId"
join "Track" as t on t."TrackId" = invl."TrackId"
join "Genre" as g on g."GenreId" = t."GenreId"
where "BillingCountry" in ('USA', 'Canada', 'Brazil', 'France', 'Germany')
group by "Invoice"."BillingCountry", g."Name") as sub1
我知道有很多针对此类错误的解决方案,但我尝试遵循这些解决方案,但我无法让查询正常工作,我只是不了解解决方案,我需要这方面的帮助。
ERROR: missing FROM-clause entry for table "g"
LINE 1: select distinct "BillingCountry", count(g."Name") as genre_o...
g.Name 列的g.Name
是子查询,所以在外部查询中是看不到的。
此外,在子查询中g.Name
别名为sub2
,因此您应该在外部查询中使用此别名。
但是,在子查询中,您group by Invoice.BillingCountry, g.Name
而不进行任何聚合。 为什么?
子查询的结果是BillingCountry
和g.Name
的所有不同组合,您也可以通过使用DISTINCT
而不是GROUP BY
获得:
select distinct BillingCountry, g.Name as sub2
from Invoice
join InvoiceLine as invl on invl.InvoiceId = Invoice.InvoiceId
join Track as t on t.TrackId = invl.TrackId
join Genre as g on g.GenreId = t.GenreId
where BillingCountry in ('USA', 'Canada', 'Brazil', 'France', 'Germany')
最后在外部查询中,您使用没有GROUP BY
子句的聚合。
也许您想在外部查询中进行聚合,如下所示:
select BillingCountry, count(Name) as genre_occurance
from (
select i.BillingCountry, g.Name
from Invoice i
join InvoiceLine as invl on invl.InvoiceId = i.InvoiceId
join Track as t on t.TrackId = invl.TrackId
join Genre as g on g.GenreId = t.GenreId
where i.BillingCountry in ('USA', 'Canada', 'Brazil', 'France', 'Germany')
) as t
group by BillingCountry
可以在没有子查询的情况下编写:
select i.BillingCountry, count(g.Name) as genre_occurance
from Invoice i
join InvoiceLine as invl on invl.InvoiceId = i.InvoiceId
join Track as t on t.TrackId = invl.TrackId
join Genre as g on g.GenreId = t.GenreId
where i.BillingCountry in ('USA', 'Canada', 'Brazil', 'France', 'Germany')
group by i.BillingCountry
您在内部查询中将 g.name 别名为 sub2,因此外部 select 不知道“名称”列,外部查询也不知道内部查询中的内容,而是您在 select 中返回的内容。 您可以像这样修复您的查询:
select distinct "BillingCountry", count(sub2) as genre_occurance
from (
select "BillingCountry", g."Name" as sub2
from "Invoice"
join "InvoiceLine" as invl on invl."InvoiceId" = "Invoice"."InvoiceId"
join "Track" as t on t."TrackId" = invl."TrackId"
join "Genre" as g on g."GenreId" = t."GenreId"
where "BillingCountry" in ('USA', 'Canada', 'Brazil', 'France', 'Germany')
group by "Invoice"."BillingCountry", g."Name"
) as sub1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.