SQL - Python - SELECT文 - 天賦のデータ検索 - 比較演算子
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 2章(SELECT文 - 天賦のデータ検索)、p.89(自分で考えてみよう)の解答を求めてみる。
schema7.sql
drop table if exists drink_info;
create table drink_info(
drink_name text,
cost real,
carbs real,
color text,
ice text,
calories integer
);
insert into drink_info (
drink_name,
cost,
carbs,
color,
ice,
calories
) values
('ブラックソーン', 3, 8.4,'黄','Y',33),
('ブルームーン', 2.5, 3.2, '青', 'Y', 12),
('オーマイゴッシュ',3.5, 8.6, '橙', 'Y', 35),
('ライムフィズ', 2.5, 5.4, '緑','Y',24),
('キンオンザリップス',5.5, 42.5, '紫', 'Y', 171),
('ホットゴールド',3.2, 32.1, '橙', 'N', 135),
('ローンツリー',3.6,4.2,'赤','Y',17),
('グレイハウンド',4,14,'黄','Y',50),
('インディアンサマー',2.8,7.2,'茶','N',30),
('ブルフロッグ',2.6,21.5,'黄褐色','Y',80),
('ソーダアンドイット',3.8,4.7,'赤','N',19);
schema7_1.sql
select cost from drink_info
where ice = 'Y'
and color = '黄'
and calories > 33;
schema7_2.sql
select drink_name, color from drink_info
where carbs <= 4
and ice = 'Y';
schema7_3.sql
select cost from drink_info
where calories >= 80;
schema7_4.sql
select drink_name, color, ice from drink_info
where cost >= 4;
コード
sample7.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
with open('schema7.sql') as f:
cur.executescript(f.read())
for i in range(1, 5):
with open(f'schema7_{i}.sql') as f:
cur.execute(f.read())
print([t[0] for t in cur.description])
for row in cur.fetchall():
print(row)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample7.py
['cost']
(4.0,)
['drink_name', 'color']
('ブルームーン', '青')
['cost']
(5.5,)
(3.2,)
(2.6,)
['drink_name', 'color', 'ice']
('キンオンザリップス', '紫', 'Y')
('グレイハウンド', '黄', 'Y')
%