SQL - SQLite - SELECT - 天賦のデータ検索 - where句、and、比較演算子
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 2章(SELECT - 天賦のデータ検索)、p.89(自分で考えてみよう)の解答を求めてみる。
drink_info.sql
begin;
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 values
('ブラックソーン',3, 3.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);
commit;
コード
sample8.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('drinks.db')
cur = con.cursor()
with open('drink_info.sql') as f:
cur.executescript(f.read())
sqls = [
'''
select cost
from drink_info
where ice = 'Y'
and color = '黄'
and calories > 33
''',
'''
select drink_name, color
from drink_info
where carbs <= 4
and ice = 'Y'
''',
'''
select cost
from drink_info
where calories >= 80
''',
'''
select color, ice
from drink_info
where cost >= 4
''',
]
for sql in sqls:
print(sql)
cur.execute(sql)
for row in cur.fetchall():
print(row)
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample8.py
select cost
from drink_info
where ice = 'Y'
and color = '黄'
and calories > 33
(4.0,)
select drink_name, color
from drink_info
where carbs <= 4
and ice = 'Y'
('ブラックソーン', '黄')
('ブルームーン', '青')
select cost
from drink_info
where calories >= 80
(5.5,)
(3.2,)
(2.6,)
select color, ice
from drink_info
where cost >= 4
('紫', 'Y')
('黄', 'Y')
%