我的情况如下(SQL: find missing IDs in a table):
我有两个表People
和Scores
,它们看起来像这样:
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
表,以包含rowID
和minScore
的{{1}}。我该怎么做?
目的:
maxScore
这就是我的尝试:
Terry | 5 | 10
Bob | 2 | 12
只使用最后一个最小值填充表格。
(我必须使用一个视图,因为我无法使用US ...)
答案 0 :(得分: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。)