計算機科学のブログ

ほしい物リスト

SQL - SQLite - Python - 外部結合、自己結合、UNION - 新しい戦略 - 左側外部結合, LEFT OUTER JOIN

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 10章(外部結合、自己結合、UNION - 新しい戦略)、p.421(自分で考えてみよう)の解答を求めてみる。

girltoy
シンディフラフープ
nullバルサ・グライダー
ジェインおもちゃの兵隊
サリーハーモニカ
null野球カード
null
null
null

schema1.sql

drop table if exists girls;
drop table if exists toys;

create table girls(
    girl_id integer primary key autoincrement,
    girl text,
    toy_id integer
);
create table toys(
    toy_id integer primary key autoincrement,
    toy text
);
insert into girls(
    girl,
    toy_id
) values
('ジェイン', 3),
('サリー', 4),
('シンディ', 1);
insert into toys(
    toy
) values
('フラフープ'),
('バルサ・グライダー'),
('おもちゃの兵隊'),
('ハーモニカ'),
('野球カード'),
('ティンカー・トイ'),
('エッチ・ア・スケッチ'),
('スリンキー');

コード

sample1.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('schema1.sql') as f:
    cur.executescript(f.read())
con.commit()

p(cur, 'girls')
p(cur, 'toys')

_sql = """
select g.girl, t.toy
from toys t
left outer join girls g
on g.toy_id = t.toy_id
"""
cur.execute(_sql)
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)

% ./sample1.py 
['girl_id', 'girl', 'toy_id']
(1, 'ジェイン', 3)
(2, 'サリー', 4)
(3, 'シンディ', 1)
['toy_id', 'toy']
(1, 'フラフープ')
(2, 'バルサ・グライダー')
(3, 'おもちゃの兵隊')
(4, 'ハーモニカ')
(5, '野球カード')
(6, 'ティンカー・トイ')
(7, 'エッチ・ア・スケッチ')
(8, 'スリンキー')
['girl', 'toy']
('シンディ', 'フラフープ')
(None, 'バルサ・グライダー')
('ジェイン', 'おもちゃの兵隊')
('サリー', 'ハーモニカ')
(None, '野球カード')
(None, 'ティンカー・トイ')
(None, 'エッチ・ア・スケッチ')
(None, 'スリンキー')
%