加入2个表和一个视图以在PostgreSQL中获得所需的结果

时间:2017-05-28 18:55:53

标签: sql postgresql

这是使用查询创建的视图:SELECT title,count(*)as views FROM articles a,log l WHERE a.slug = substring(l.path,10)GROUP BY title ORDER BY views DESC;

      title   | views
 ------------------------------------+--------
  article-1   | 338647
  article-2   | 253801
  article-5   | 170098
  article-3   |  84906
  article-8   |  84810
  article-7   |  84557
  article-6   |  84504
  article-4   |  84383

现在我正在尝试使用此视图创建一个查询,以打印出与标题关联的每个作者的文章视图总和。下面我重新创建了其他两个表的关键列。

  AUTHORS
           name       | id
 ---------------------+--------
          author-1    | 1
          author-2    | 2
          author-3    | 3
          author-4    | 4

 ARTICLES
    author     | article
 --------------+--------
          1    | article-1
          2    | article-2
          1    | article-3
          4    | article-4
          1    | article-5
          1    | article-6
          3    | article-7
          2    | article-8

1 个答案:

答案 0 :(得分:0)

你会这样做:

select a.author, sum(v.views) as view
from yourview v join
     articles a
     on v.title = a.article join
     authors au
     on a.author = au.id
group by a.author;