計算機科学のブログ

SQL - SQLite - Python - 複数テーブルのデータベース設計 - 現行テーブルからの脱却 - データのパターン, 多対多, 外部キー

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 7章(複数テーブルのデータベース設計 - 現行テーブルからの脱却)、p.313(自分で考えてみよう)の解答を求めてみる。

schema7.sql

PRAGMA foreign_keys = ON;
create table shoes(
    shoe_id integer primary key autoincrement,
    shoe_name text
);
create table woman (
    woman_id integer primary key autoincrement,
    woman text,
    shoe_id integer,
    foreign key (shoe_id) references shoes (shoe_id)
);
insert into shoes(
    shoe_name
) values
('マノロのストラップサンダル'),
('クロックスのクロッグズ'),
('オールド・ネイビーのサンダル'),
('プラダのブーツ');
insert into woman(
    woman,
    shoe_id
) values
('キャリー', 3),
('サマンサ', 1),
('シャルロット', 1),
('ミランダ', 1),
('キャリー', 4),
('シャルロット', 2),
('シャルロット', 3),
('シャルロット', 4),
('ミランダ', 3),
('ミランダ', 4);

コード

sample7.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)


with open(f'schema7.sql') as f:
    cur.executescript(f.read())
con.commit()

p(cur, 'woman')
p(cur, 'shoes')

cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample7.py 
['woman_id', 'woman', 'shoe_id']
(1, 'キャリー', 3)
(2, 'サマンサ', 1)
(3, 'シャルロット', 1)
(4, 'ミランダ', 1)
(5, 'キャリー', 4)
(6, 'シャルロット', 2)
(7, 'シャルロット', 3)
(8, 'シャルロット', 4)
(9, 'ミランダ', 3)
(10, 'ミランダ', 4)
['shoe_id', 'shoe_name']
(1, 'マノロのストラップサンダル')
(2, 'クロックスのクロッグズ')
(3, 'オールド・ネイビーのサンダル')
(4, 'プラダのブーツ')
%