SQLite Order By foreign table 字段

SQLite Order By foreign table field

我有两个表如下:(实际上它们有更多的字段)

Records (
    recordId INTEGER PRIMARY KEY,
    dateTime TEXT
);

Alarms (
    alarmId INTEGER PRIMARY KEY,
    recordId INTEGER,
    FOREIGN KEY (recordId) REFERENCES Records(recordId)
    ON UPDATE CASCADE
    ON DELETE CASCADE
);

我想按 dateTime 引用的记录对所有警报进行排序。我认为应该是这样的:

SELECT * FROM Alarms ORDER BY Records.dateTime DESC;

但是我找不到任何相关的例子。 谢谢你的时间。

您需要连接 2 个表:

SELECT a.* 
FROM Alarms a INNER JOIN Records r
ON r.recordId = a.recordId 
ORDER BY r.dateTime DESC;

ORDER BY子句中的相关子查询:

SELECT a.* 
FROM Alarms a 
ORDER BY (SELECT r.dateTime FROM Records r WHERE r.recordId = a.recordId) DESC;