SQL - SQLite - 結合と複数テーブル操作 - みんなでうまくやれないの? - 文字列、substring, instr, length関数
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 8章(結合と複数テーブル操作 - みんなでうまくやれないの?)、p.350(自分で考えてみよう)の解答を求めてみる。
sample3.sql
drop table if exists temp;
create table temp
(
interests text,
interest1 text,
interest2 text,
interest3 text,
interest4 text
);
insert into temp
(interests)
values
('第1、第2、第3、第4');
コード
sample3.py
#!/usr/bin/env python3
import sqlite3
con = sqlite3.connect('gregs_list.db')
cur = con.cursor()
def p():
sql = """select * from temp"""
cur.execute(sql)
for row in cur.fetchall():
print(row)
with open('sample3.sql') as f:
cur.executescript(f.read())
p()
for i in range(1, 4):
sql = f"""
update temp set
interest{i} = substr(interests, 1, instr(interests, '、') - 1);
update temp set
interests = substr(interests, length(interest{i}) + 2)
"""
cur.executescript(sql)
p()
sql = """
update temp set
interest4 = interests,
interests = null
"""
cur.execute(sql)
con.commit()
p()
入出力結果(Terminal, Zsh)
% ./sample3.py
('第1、第2、第3、第4', None, None, None, None)
('第2、第3、第4', '第1', None, None, None)
('第3、第4', '第1', '第2', None, None)
('第4', '第1', '第2', '第3', None)
(None, '第1', '第2', '第3', '第4')
%