SQL - SQLite - Python - 複数テーブルのデータベース設計 - 現行テーブルからの脱却 - ANDとOR
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 7章(複数テーブルのデータベース設計 - 現行テーブルからの脱却)、p.291(エクササイズ)の解答を求めてみる。
schema5.sql
select * from my_contacts
where gender = '女性'
and birthday > '1955/03/20'
and birthday < '1960/03/20'
and state = 'マサチューセッツ州'
and status = '独身'
and seeking = '独身男性'
and (
interest1 = '動物'
or interest2 = '動物'
or interest3 = '動物'
or interest4 = '動物'
) and (
interest1 = 'トレーディングカード'
or interest2 = 'トレーディングカード'
or interest3 = 'トレーディングカード'
or interest4 = 'トレーディングカード'
) and (
interest1 = 'ジオキャッシング'
or interest2 = 'ジオキャッシング'
or interest3 = 'ジオキャッシング'
or interest4 = 'ジオキャッシング'
);
コード
sample5.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
def p(cur: sqlite3.Cursor, table: str):
cur.execute(
f"""
select * from {table}
"""
)
if (d := cur.description) is not None:
print([t[0] for t in d])
for row in cur.fetchall():
print(row)
p(cur, 'my_contacts')
with open(f'schema5.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(dict(row))
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample5.py
['contact_id', 'last_name', 'first_name', 'phone', 'email', 'gender', 'birthday', 'profession', 'city', 'state', 'status', 'interest1', 'interest2', 'interest3', 'interest4', 'seeking']
(1, 'アンダーソン', 'ジリアン', None, 'jill_anderson@breaknechpizza.com', 'F', '1980-09-05', 'テクニカルライター', None, None, '独身', 'カヤック乗り', '爬虫類', None, None, '恋人、友達')
['contact_id', 'last_name', 'first_name', 'phone', 'email', 'gender', 'birthday', 'profession', 'city', 'state', 'status', 'interest1', 'interest2', 'interest3', 'interest4', 'seeking']
%