如何在python中查询sqlite3中的4个表?

时间:2016-03-11 03:31:07

标签: python sqlite

这是我的表格。我得到0行返回。

CREATE TABLE Artist (
    id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    name    TEXT UNIQUE
);
CREATE TABLE Album (
    id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    artist_id  INTEGER,
    title   TEXT UNIQUE
);
CREATE TABLE Genre (
    id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    name    TEXT
);
CREATE TABLE Track (
    id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    title TEXT  UNIQUE,
    album_id  INTEGER,
    genre_id INTEGER,
    len INTEGER, rating INTEGER, count INTEGER
);

这是我的SQL代码:

SELECT Track.title, Artist.name, Album.title, Genre.name 
FROM Track JOIN Genre JOIN Album JOIN Artist 
ON Track.genre_id = Genre.id and Track.album_id = Album.id 
WHERE Album.artist_id = Artist.id
ORDER BY Artist.name LIMIT 3

感谢您调查此问题。

1 个答案:

答案 0 :(得分:1)

您的代码是正确的,但您需要用刚刚创建的表填充记录。

例如,通过运行(未经测试):

INSERT INTO Artist (name) VALUES ('Artist 1'), ('Artist 2');
INSERT INTO Genre (name) VALUES ('Genre 1'), ('Genre 2');

INSERT INTO Album (title, artist_id) VALUES ('Title 1', 1);

INSERT INTO Track(title, album_id, 
    genre_id, len, rating, count) 
    VALUES ('Track 1', 1, 1, 0, 0, 0);

此外,您应将artist_idalbum_idgenre_id列声明为foreign keys