0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React + Expressで作るカート画面:商品情報とレビュー集計を含めたSQLクエリの設計

Posted at

はじめに

React と Express を使ってカート画面を構築する中で、
以下のような要件を満たすために SQL 設計を工夫しました。

  • 商品名、価格、数量の表示
  • 各商品のレビュー平均点とレビュー数の表示
  • 特定ユーザーのカート内容だけを対象にする

カートと商品、レビューのテーブル関係

簡易的な ER 図は以下のようになります:

USER (1) ─── (∞) CART (∞) ─── (1) PRODUCT (1) ─── (∞) REVIEW


要件:ログインユーザーのカートにある商品のレビュー情報を一緒に表示したい

解決方法:サブクエリ+LEFT JOIN

SELECT
  C.cart_id,
  C.quantity,
  P.product_id,
  P.name,
  P.price,
  COALESCE(R.review_avg, 0) AS average_rating,
  COALESCE(R.review_count, 0) AS review_count
FROM cart AS C
JOIN product AS P ON C.product_id = P.product_id
LEFT JOIN (
  SELECT
    product_id,
    AVG(rating) AS review_avg,
    COUNT(*) AS review_count
  FROM review
  WHERE is_deleted = false
  GROUP BY product_id
) AS R ON R.product_id = P.product_id
WHERE C.user_id = ?
  AND C.is_deleted = false;

まとめ
実装中に気をつけた点:

データ構造を理解して結合順序と集約方法を選ぶ

ユーザーのセキュリティを守るために user_id 条件は必須

COALESCE で NULL を 0 にすることで UI 側でも処理が簡単に

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?