0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【MySQL】条件によってVIEWの表示結果を分岐する ~ case when ~

Last updated at Posted at 2020-06-02

条件によってVIEWの表示結果を分岐させる書き方のサンプル集です。

環境

  • OS:Windows10
  • RDBMS:MySQL5.7

case whenサンプル

1. 条件によって表示結果を分岐する

合計得点に応じて、成績表記を分岐します。
テーブルとその関係性は以下の通り。
※実際にはこんなテーブルはないと思いますが、サンプルのためご容赦を。
image.png

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を表示させます。
以下は、とあるユーザーの対象店舗に対するブックマークの有無になります。
テーブルとその関係性は以下の通り。
image.png

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負荷の考慮は必要ですが、うまく使っていきたいと思います。

参考

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?