如何做一个Postgresql子查询的select子句与像SQL Server一样的join子句?

前端之家收集整理的这篇文章主要介绍了如何做一个Postgresql子查询的select子句与像SQL Server一样的join子句?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图写下面的查询postgresql
select name,author_id,count(1),(select count(1)
    from names as n2
    where n2.id = n1.id
        and t2.author_id = t1.author_id
    )               
from names as n1
group by name,author_id

这将肯定工作在Microsoft sql Server,但它根本不在postegresql。我读了它的文档有点,它似乎我可以重写它:

select name,total                     
from names as n1,(select count(1) as total
    from names as n2
    where n2.id = n1.id
        and n2.author_id = t1.author_id
    ) as total
group by name,author_id

但是这会在postegresql上返回以下错误:“FROM中的子查询不能引用同一查询级别的其他关系”。所以我被卡住了。有谁知道我怎么能实现呢?

谢谢

我不知道我完全理解你的意图,但也许以下将接近你想要的:
select n1.name,n1.author_id,count_1,total_count
  from (select id,name,count(1) as count_1
          from names
          group by id,author_id) n1
inner join (select id,count(1) as total_count
              from names
              group by id,author_id) n2
  on (n2.id = n1.id and n2.author_id = n1.author_id)

不幸的是,这增加了按照id以及name和author_id对第一个子查询进行分组的要求,我认为这是不需要的。我不知道如何解决,但是,因为你需要有id可用于加入第二个子查询。也许别人会想出一个更好的解决方案。

分享和享受。

原文链接:https://www.f2er.com/postgresql/193405.html

猜你在找的Postgre SQL相关文章