加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:45:14 所属栏目:百科 来源:网络整理
导读:我试图写下面的查询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 n1group by name,author_id 这将肯定工作在Microsoft SQL Server,但它根本不在p
我试图写下面的查询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可用于加入第二个子查询。也许别人会想出一个更好的解决方案。

分享和享受。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读