如何做一个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可用于加入第二个子查询。也许别人会想出一个更好的解决方案。

分享和享受。

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...