2017-05-25 87 views
0

我的情況如下(SQLfiddle)給出:SQLite的更新多條記錄與不同的值由查詢

我有兩個表PeopleScores,他們看起來是這樣的:

CREATE TABLE People 
(
    name TEXT, 
    minScore INTEGER, 
    maxScore INTEGER, 
    FOREIGN KEY (minScore) REFERENCES B(rowid), 
    FOREIGN KEY (maxScore) REFERENCES B(rowid) 
); 

INSERT INTO People (name) VALUES ('Terry'); 
INSERT INTO People (name) VALUES ('Bob'); 

CREATE TABLE Scores 
(
    nameID INTEGER, 
    score INTEGER, 
    FOREIGN KEY (nameID) REFERENCES A(rowid) 
); 

INSERT INTO Scores (nameID, score) VALUES (1, 10); 
INSERT INTO Scores (nameID, score) VALUES (1, 8); 
INSERT INTO Scores (nameID, score) VALUES (1, 5); 
INSERT INTO Scores (nameID, score) VALUES (2, 12); 
INSERT INTO Scores (nameID, score) VALUES (2, 8); 
INSERT INTO Scores (nameID, score) VALUES (2, 2); 

我想更新People表以包含其minScoremaxScorerowID。我怎麼做?

目的:

Terry | 5 | 10 
Bob | 2 | 12 

這是我曾嘗試:

CREATE VIEW minScores 
AS 
    SELECT Scores.rowid AS scoreID, Scores.nameID AS nameID 
    FROM Scores 
    WHERE score IN (SELECT MIN(score) 
        FROM Scores AS Scores2 
        GROUP BY Scores2.nameID); 

UPDATE People 
SET minScore = (SELECT scoreID FROM minScores) 
WHERE People.rowid IN (SELECT nameID FROM minScores) 

剛剛填充表的最後一個最小值。

(我不得不使用一個觀點,因爲我無法瞭解如何使用工作...)

+0

謝謝你爲編輯@CL。這讀起來好多了。 – NE5534

回答

1

你更新使用scalar subquery;其值

是所附SELECT語句結果的第一行。換句話說,隱含的「LIMIT 1」被添加到子查詢中。

要獲取不同的行不同的結果,你必須使用一個correlated subquery

UPDATE People 
SET minScore = (SELECT rowid 
       FROM Scores 
       WHERE Scores.nameID = People.rowid 
       ORDER BY score ASC), 
    maxScore = (SELECT rowid 
       FROM Scores 
       WHERE Scores.nameID = People.rowid 
       ORDER BY score DESC); 

(你不應該使用外鍵隱含rowid;其價值can change

+0

謝謝@CL。今天早上我會在火車上多學習一點。我不知道不使用rowid,我被告知,它比創建ID密鑰更好,但我認爲我的講師並不知道它可能會改變(除非我得到了錯誤的結尾)。 – NE5534

相關問題