如何从sqlite3 python中的子键检索父键中的特定数据字段?
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER PRIMARY KEY,
trackname TEXT,
artistid INTEGER
FOREIGN KEY(artistid) REFERENCES artist(artistid)
);
track.execute('''SELECT artisid, trackname FROM track WHERE artistid = 1''')
所以假设现在我已经执行了轨道表,我得到了artisid和trackname,我也想检索artisname,并把它放在两者之间,我该怎么做?
答案 0 :(得分:1)
如果您已拥有艺术家ID,则可以执行简单的SELECT
:
SELECT artistname FROM artist WHERE artistid = ?
如果要在同一查询中检索名称,则必须加入两个表:
SELECT artist.artistid,
artist.artistname,
track.trackname
FROM track JOIN artist ON track.artistid = artist.artistid
WHERE artist.artistid = ?