我在使用Python编写sqlite3数据库时遇到问题。
所以我做了两个清单:
idata=[(0,"Ingredient1"),
(1,"Ingredient2")]
这是第一个拥有" Ingredients"和他们的ID。
rdata=[(0,"Recipie1",0,1,1)]
这是第二个拥有" Recipies"他们的ID和三个数字表示"成分"在这个" Recipie"中使用。
然后我创建了两个表格,我填写了这些列表的数据:
import sqlite3
conn = sqlite3.connect ("Alchemy_Data_Bank.dat")
c = conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS recipie(id, name, iid_1, iid_2, iid_3);
""")
c.executemany("insert into recipie(id, name, iid_1, iid_2, iid_3) values (?,?,?,?,?)", rdata)
c.execute("""
CREATE TABLE IF NOT EXISTS ingredient(id, name);
""")
c.executemany("insert into ingredient(id, name) values (?,?)", idata)
conn.commit()
现在我要打印出" Recipies"和他们的"成分"合并在一张桌子里。所以我这样做了:
for p in c.execute("""SELECT DISTINCT recipie.name,
CASE WHEN recipie.iid_1 = ingredient.id THEN ingredient.name end,
CASE WHEN recipie.iid_2 = ingredient.id THEN ingredient.name end,
CASE WHEN recipie.iid_3 = ingredient.id THEN ingredient.name end
FROM recipie, ingredient;"""):
print(p)
c.close()
conn.close()
我希望得到的输出是这样的:
('Recipie1','Ingredient1', 'Ingredient2', 'Ingredient2')
但它打印了这个:
('Recipie1', None, None, None)
('Recipie1', None, 'Ingredient2', 'Ingredient2')
('Recipie1', 'Ingedient1', None, None)
我认为我的问题存在于CASE WHEN状态中,因为programm一次比较recipie.iid_1,recipie.iid_2和recipie.iid_3只有一个值为ingredient.id。 到目前为止,解决方案必须在每个案例中进行递归选择,但我无法弄清楚如何做到这一点。
我希望有人能告诉我怎么做!
提前致谢!!
Cazo0
答案 0 :(得分:0)
尝试重写查询。 e.g:
qry1 = """select name,
(select name from ingredient where ingredient.id = recipie.iid_1),
(select name from ingredient where ingredient.id = recipie.iid_2),
(select name from ingredient where ingredient.id = recipie.iid_3)
from recipie;"""
rsl = c.execute(qry1)
for r in rsl:
print (r)
查看我的要点: https://gist.github.com/mh70cz/5cfa595b455e87d7c08da5315b1abd21