python函数中的sql
我有以下表格:python函数中的sql,python,sql,Python,Sql,我有以下表格: table1: name born country id A 1943 UK 3 B 1966 USA 2... table2: artist_id artist_name formation 3 The Beatles 1960 2 The Door USA 所以我正在努力写下面的函数,有人能给我一个开始的想法吗 def ban
table1: name born country id
A 1943 UK 3
B 1966 USA 2...
table2: artist_id artist_name formation
3 The Beatles 1960
2 The Door USA
所以我正在努力写下面的函数,有人能给我一个开始的想法吗
def band_by_country(sql_cursor,country):
'''(sqlite3.Cursor,str)->list of[]
return a list of bands representing all the bands who have at least one member who was born in that country.
>>>band_by_country(sql_cursor, UK)
['The Beatles']
>>>band_by_country(sql_cursor,USA)
['The Doors']
'''
假设您的连接已经设置好,下面应该为您提供表中的name参数
def band_by_country(sql_cursor,country):
bands = []
for row in sql_cursor.execute('SELECT name FROM table1 WHERE country=?', (country,)):
bands.append( row[0] )
return bands
如果要将表1与表2连接起来,它将如下所示:
def band_by_country(sql_cursor,country):
bands = []
for row in sql_cursor.execute(
"SELECT table2.artist_name FROM table1 JOIN table2 ON "
"table1.id=table2.artist_id WHERE table1.country=?", (country,)):
bands.append( row[0] )
return bands
我会让这个选择不同,否则你的第二个查询看起来不错。有一些乐队同名。如果数据库中有两行,那么我不想从结果中删除它们。