作成日:2020-09-08, 更新日:2020-09-08
やりたいこと
・テーブルに登録されていないデータを探したい
流れ
・探したいデータでテーブルっぽいものを作成(union all)
・対象のレコードから存在するか検索(not exists)
・2つを合体(with)
探したいデータでテーブルっぽいものを作成(union all)
▼unionでselectを接続して、テーブルっぽいものを作成
select '鶏精' as `hoge` union all select 'ささみおろしポン酢' as `hoge`
「union」と「union all」
詳細は・・・未調査。ひとまずメモだけ。
・重複データが存在する場合、「union」を使う。
・「union」は遅い、「union all」は速い
→特に問題ないなら「union all」を使えば良い
対象のレコードから存在するか検索
▼not existsで存在しない条件を作成
where not exists (select * from AAA where BBB.`hoge` = AAA.`hoge`)
2つを合体
▼withを使う
with BBB as ( select '鶏精' as `hoge` union all select 'ささみおろしポン酢' as `hoge` ) select `BBB`.`hoge` from `BBB` where not exists (select * from AAA where BBB.`hoge` = AAA.`hoge`)