SQL - SQLite - 結合と複数テーブル操作 - みんなでうまくやれないの? - inner join
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 8章(結合と複数テーブル操作 - みんなでうまくやれないの?)、p.351(エクササイズ - 気楽にやってみよう)の解答を求めてみる。
mc.last_name | mc.first_name | p.profession |
---|---|---|
エヴェレット | ジョーン | アーティスト |
シン | ポール | 教授 |
ボールドウィン | タラ | シェフ |
sample5.sql
pragma foreign_keys = on;
drop table if exists profession;
drop table if exists my_contacts;
create table profession
(
prof_id integer primary key autoincrement,
profession text
);
insert into profession
(profession)
values
('アーティスト'),
('教授'),
('シェフ');
create table my_contacts
(
contact_id integer primary key autoincrement,
last_name text,
first_name text,
phone text,
email text,
gender text,
birthday text,
prof_id integer,
foreign key(prof_id) references profession(prof_id)
);
insert into my_contacts
(first_name, last_name, prof_id)
values
('ジョーン', 'エヴェレット', 1),
('ポール','シン',2),
('タラ','ボールドウィン',3);
コード
sample5.py
#!/usr/bin/env python3
import sqlite3
con = sqlite3.connect('gregs_list.db')
cur = con.cursor()
with open('sample5.sql') as f:
cur.executescript(f.read())
sql = """
select mc.last_name, mc.first_name, p.profession
from my_contacts mc
inner join profession p
on mc.prof_id = p.prof_id
"""
cur.execute(sql)
for row in cur.fetchall():
print(row)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample5.py
('エヴェレット', 'ジョーン', 'アーティスト')
('シン', 'ポール', '教授')
('ボールドウィン', 'タラ', 'シェフ')
%