子查询中的计数/求和值和它的顺序

时间:2016-05-01 02:28:09

标签: sql postgresql join subquery aggregate

我有以下表格:

user
    id | status
    1  | 0

gallery 
    id | status | create_by_user_id 
    1  | 0      | 1
    2  | 0      | 1
    3  | 0      | 1

media      
    id | status
    1  | 0
    2  | 0
    3  | 0

gallery_media      
         fk gallery.id fk media.id
    id | gallery_id | media_id | sequence
    1  | 1          | 1        | 1
    2  | 2          | 2        | 1
    3  | 2          | 3        | 2

monitor_traffic
                                  1:gallery 2:media
    id | anonymous_id | user_id | endpoint_code | endpoint_id
    1  | 1            |         | 1             | 2      gallery.id 2
    2  | 2            |         | 1             | 2      gallery.id 2
    3  |              | 1       | 2             | 3      media.id 3 include in gallery.id 2
    these means gallery.id 2 contain 3 rows 

gallery_information
         fk gallery.id    
    id | gallery_id    

gallery包括media

monitor_traffic.endpoint_code1 ..画廊; 2媒体
如果1,则monitor_traffic.endpoint_id引用gallery.id

monitor_traffic.user_idmonitor_traffic.anonymous_id整数或null

目标

我想输出gallery行,按gallery中的每个monitor_traffic行计算,然后计算gallery中的media相关monitor_traffic行}。最后总结一下。

我提供的查询仅在media中计算monitor_traffic而不对其进行求和,也不计算gallery中的monitor_traffic

怎么做?

这是函数的一部分,输入选项然后输出构建查询,类似于this。我希望找到一个解决方案(可能带有子查询),不需要更改查询的其他部分。

查询:

SELECT
  g.*,
  row_to_json(gi.*) as gallery_information
  FROM gallery g 
  LEFT JOIN gallery_information gi ON gi.gallery_id = g.id
  LEFT JOIN "user" u ON u.id = g.create_by_user_id
  -- start    
  LEFT JOIN gallery_media gm ON gm.gallery_id = g.id
  LEFT JOIN (
    SELECT 
      endpoint_id, 
      COUNT(*) as mt_count
      FROM monitor_traffic
      WHERE endpoint_code = 2
      GROUP BY endpoint_id
  ) mt ON mt.endpoint_id = m.id
  -- end
ORDER BY mt.mt_count desc NULLS LAST;

sql fiddle

1 个答案:

答案 0 :(得分:1)

我建议CTE计算一个聚合中的两种类型,并在FROM子句中连接两次:

WITH mt AS (  -- count once for both media and gallery
   SELECT endpoint_code, endpoint_id, count(*) AS ct
   FROM   monitor_traffic
   GROUP  BY 1, 2
   )
SELECT g.*, row_to_json(gi.*) AS gallery_information
FROM   gallery g
LEFT   JOIN mt ON mt.endpoint_id = g.id  -- 1st join to mt
              AND mt.endpoint_code = 1   -- gallery
LEFT   JOIN (
   SELECT gm.gallery_id, sum(ct) AS ct
   FROM   gallery_media gm 
   JOIN   mt ON mt.endpoint_id = gm.media_id  -- 2nd join to mt
            AND mt.endpoint_code = 2          -- media
   GROUP  BY 1
   ) mmt ON mmt.gallery_id = g.id
LEFT   JOIN gallery_information gi ON gi.gallery_id = g.id
ORDER  BY mt.ct DESC NULLS LAST   -- count of galleries
       , mmt.ct DESC NULLS LAST;  -- count of "gallery related media"

或者,按两个计数的总和排序:

...
ORDER  BY COALESCE(mt.ct, 0) + COALESCE(mmt.ct, 0) DESC;

首先聚合,然后加入。这可以防止使用“代理交叉连接”的复杂性,即行数:

LEFT JOIN"user"似乎是死货。删除它:
<击> LEFT JOIN "user" u ON u.id = g.create_by_user_id

不要使用"user"之类的保留字作为标识符,即使只要双引号也允许这样做。非常容易出错。