0

如何从 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 并将它放在两者之间,我该怎么做?

4

1 回答 1

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 = ?
于 2013-04-13T08:11:38.180 回答