我有以下表格:
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_code
:1
..画廊; 2
媒体
如果1
,则monitor_traffic.endpoint_id
引用gallery.id
monitor_traffic.user_id
,monitor_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;
答案 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"
之类的保留字作为标识符,即使只要双引号也允许这样做。非常容易出错。