我想在创建数据库视图方面获得一些帮助。我的数据库架构如下所示:
products (id, ignored_comments_ids (array))
activities (id)
comments (id)
activities_comments (activity_id comment_id)
products_comments (product_id, comment_id)
offers (product_id, activity_id)
现在我需要使用名为的自定义列创建所有产品评论的视图source
:
source
= 'OFFER': 来自products.offers.activities.comments
协会的评论source
= 'DIRECT':来自products.comments
关联的评论此外,该视图应排除来自
products.ignored_comments_ids
我怎么做?视图必须具有product_id
,source
以及表中的所有列comments
。
我想出了以下观点,我该如何改进它?
CREATE OR REPLACE VIEW all_comments AS
WITH the_comments AS (
SELECT
comments.*,
'OFFER' AS source,
products.id AS product_id
FROM comments
JOIN activities_comments ON activities_comments.comment_id = comments.id
JOIN activities ON activities.id = activities_comments.activity_id
JOIN offers ON offers.activity_id = activities.id
JOIN products ON products.id = offers.product_id
UNION
SELECT
comments.*,
'DIRECT' AS source,
products.id AS product_id
FROM comments
JOIN products_comments ON products_comments.comment_id = comments.id
JOIN products ON products.id = products_comments.product_id
)
SELECT DISTINCT ON (the_comments.id)
the_comments.id,
the_comments.name,
the_comments.source,
the_comments.product_id
FROM the_comments
JOIN products ON products.id = the_comments.product_id
WHERE NOT to_json(products.ignored_comment_ids)::jsonb @> the_comments.id::jsonb
ORDER BY the_comments.id;