計算機科学のブログ

SQL - Python - SELECT文 - 天賦のデータ検索 - where句, OR, AND

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 2章(SELECT文 - 天賦のデータ検索)、p.97(条件文になってみよう)の解答を求めてみる。

schema9.sql

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 (
    location,
    time,
    date,
    type,
    rating,
    comments
) values
('クリスピーキング', '午前 8:50', '9/27', 'プレーンキレーズド', 10, 'ほとんど完壁'),
('ダンカンズドーナツ', '午前 8:59', '8/25', NULL, 6, '油っこい'),
('スターバズコーヒー', '午後 7:35', '5/24', 'シナモンケーキ', 5, '堅いけど、おいしい'),
('スターバズコーヒー', '午後 7:03', '4/26', 'シャム', 7, 'シャムが足りない');

schema9_0.sql

select type from doughnut_ratings
where location = 'クリスピーキング'
and rating <> 6; 
-- プレーンキレーズド

schema9_1.sql

select type from doughnut_ratings
where location = 'クリスピーキング'
and rating = 3; 
-- 該当なし

schema9_2.sql

select type from doughnut_ratings
where location = 'スナッピーベーグル'
and rating >= 6; 
-- 該当なし

schema9_3.sql

select type from doughnut_ratings
where location = 'クリスピーキング'
or rating > 5; 
-- プレーングレーズド
-- NULL
-- ジャム

schema9_4.sql

select type from doughnut_ratings
where location = 'クリスピーキング'
or rating = 3; 
-- プレーンキレーズド

schema9_5.sql

select type from doughnut_ratings
where location = 'スナッピーベーグル'
and rating = 6; 
-- NULL

コード

sample9.py

#! /usr/bin/env python3
import sqlite3

con = sqlite3.connect('sample.db')
cur = con.cursor()

with open('schema9.sql') as f:
    cur.executescript(f.read())

for i in range(6):
    with open(f'schema9_{i}.sql') as f:
        cur.execute(f.read())
    if (d := cur.description) is not None:
        print([t[0] for t in d])
    for row in cur.fetchall():
        print(row)

cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample9.py
['type']
('プレーンキレーズド',)
['type']
['type']
['type']
('プレーンキレーズド',)
(None,)
('シャム',)
['type']
('プレーンキレーズド',)
['type']
%