我有一个在MYSQL中运行的查询,但不会在SQLite中运行。我认为它失败是因为WHERE子句中有多个参数。
目的是为所有调查问题(sqid)选择唯一的最新调查答案(said),因为一个问题可能有多个答案。

SELECT sqid, said, saname, satimestamp
FROM surveyanswer
WHERE (sqid, hoid, satimestamp) IN (
    SELECT sqid, hoid, max(satimestamp) as satimestamp
    FROM surveyanswer
    GROUP BY sqid
)

我试过用satimestamp排序,选择了一个限制值,而不是max,但无法使其工作。

最佳答案

您可以使用联接来执行此操作:

SELECT sqid, said, saname, satimestamp
FROM surveyanswer A
JOIN (
    SELECT sqid, hoid, max(satimestamp) as satimestamp
    FROM surveyanswer
    GROUP BY sqid
) B ON A.sqid = B.sqid and A.hoid = B.hoid and A.satimestamp = B.satimestamp

这在功能上与您最初的SQL类似,但由于您只关心时间,因此我相信这也会起作用:
SELECT sqid, said, saname, satimestamp
FROM surveyanswer A
JOIN (
    SELECT max(satimestamp) as satimestamp
    FROM surveyanswer
) B ON A.satimestamp = B.satimestamp

07-27 19:45