データベース ビューを作成する際に助けが必要です。私のDBスキーマは次のようになります。
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
products.offers.activities.comments
= 'OFFER':協会からのコメントsource
products.comments
= 'DIRECT':協会からのコメントまた、ビューはコメントを除外する必要があります
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;