1

データベース ビューを作成する際に助けが必要です。私の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

  • sourceproducts.offers.activities.comments= 'OFFER':協会からのコメント
  • sourceproducts.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;
4

1 に答える 1