SQL - SQLite - SELECT - 天賦のデータ検索 - where句、条件文、ANDとOR
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 2章(SELECT - 天賦のデータ検索)、p.97(条件文になってみよう)の解答を求めてみる。
doughnut_ratings.sql
begin;
drop table if exists doughnut_ratings;
create table doughnut_ratings (
location text,
time text,
date text,
type text,
rating integer,
comments text
);
insert into doughnut_ratings values
('クリスピーキング', '午前 8:50', '9/27', 'プレーングレーズド', 10, 'ほとんど完璧'),
('ダンカンズドーナツ', '午前 8:59', '8/25', null, 6, '油っこい'),
('スターバズコーヒー', '午後 7:35', '5/24', 'シナモンケーキ', 5, '堅いけど、おいしい'),
('スターバズコーヒー', '午後 7:03', '4/26', 'ジャム', 7, 'ジャムが足りない');
commit;
コード
sample10.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('doughnut.db')
cur = con.cursor()
with open('doughnut_ratings.sql') as f:
cur.executescript(f.read())
wheres = [
"location = 'クリスピーキング' and rating <> 6", # プレーングレーズド
"location = 'クリスピーキング' and rating = 3", # なし
"location = 'スナッピーベーグル' and rating >= 6", # なし
"location = 'クリスピーキング' or rating > 5", # プレーングレーズド, null, ジャム
"location = 'クリスピーキング' or rating = 3", # プレーングレーズド
"location = 'スナッピーベーグル' or rating = 6", # null
]
for where in wheres:
sql = f'''
select type from doughnut_ratings where {where}
'''
print(sql)
cur.execute(sql)
for row in cur.fetchall():
print(row)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample10.py
select type from doughnut_ratings where location = 'クリスピーキング' and rating <> 6
('プレーングレーズド',)
select type from doughnut_ratings where location = 'クリスピーキング' and rating = 3
select type from doughnut_ratings where location = 'スナッピーベーグル' and rating >= 6
select type from doughnut_ratings where location = 'クリスピーキング' or rating > 5
('プレーングレーズド',)
(None,)
('ジャム',)
select type from doughnut_ratings where location = 'クリスピーキング' or rating = 3
('プレーングレーズド',)
select type from doughnut_ratings where location = 'スナッピーベーグル' or rating = 6
(None,)
%