条件によってVIEWの表示結果を分岐させる書き方のサンプル集です。
環境
- OS:Windows10
- RDBMS:MySQL5.7
case whenサンプル
1. 条件によって表示結果を分岐する
合計得点に応じて、成績表記を分岐します。
テーブルとその関係性は以下の通り。
※実際にはこんなテーブルはないと思いますが、サンプルのためご容赦を。
create view score_reports
as select
sr.*,
case
when sr.total_score >= 85 then '優'
when sr.total_score >= 70 then '良'
when sr.total_score >= 60 then '可'
else '不可' end as grade
from
(select
st.student_name,
su.subject_name,
sc.score,
(select sum(score) from scores group by student_id and test_month) as total_score
from students st
left outer join scores sc on st.student_id = sc.student_id
cross join subjects su) as sr;
2. 結果の有無によって表示結果を分岐する
対象が存在すれば1、なければ0を表示させます。
以下は、とあるユーザーの対象店舗に対するブックマークの有無になります。
テーブルとその関係性は以下の通り。
create view shop_informations
as select
si.*,
case when exists (select * from bookmarks b where b.shop_id = si.shop_id and b.user_id = si.user_id) then 1 else 0 end as is_bookmarked
from
(select
s.shop_id,
s.shop_name,
u.user_id
from shops s cross join users u) as si;
終わりに
case式を使えば、アプリケーションの実装をシンプル&わかりやすくできそうですね。
DB負荷の考慮は必要ですが、うまく使っていきたいと思います。