2013-11-26 85 views
2

我有這個查詢在MYSQL中工作,但不會在SQLite中運行。我認爲它由於WHERE子句中的多個參數而失敗。SQLite在WHERE中傳遞多個參數

目的是爲所有調查問題(sqid)選擇唯一的最新調查答案(表示),因爲對問題的多個答案是可能的。

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與訂貨試驗和選擇的一個,而不是最大的限制,但不能得到它的工作。

+0

即使SQLite的會支持你的元組比較仍由於「非法」使用「GROUP BY」,因此在您的子選擇中出現錯誤:http://www.mysqlperformanceblog.com/2006/09/06/wrong-group-by-makes-your-queries-脆弱/ –

回答

2

你可以做到這一點聯接:

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 
2

一點也沒有看起來你沒有使用hoid這個字段。所以,我刪除了它。執行以下操作產生你在找什麼:

SELECT sa.sqid, sa.said, sa.saname, sa.satimestamp 
FROM surveyanswer sa 
WHERE sa.satimestamp IN (
    SELECT max(subsa.satimestamp) 
    FROM surveyanswer subsa 
    WHERE sa.sqid = subsa.sqid 
) 

如果hoid領域需要包含在where子句中,然後嘗試以下方法:

SELECT sa.sqid, sa.said, sa.saname, sa.satimestamp 
FROM surveyanswer sa 
WHERE sa.satimestamp IN (
    SELECT max(subsa.satimestamp) 
    FROM surveyanswer subsa 
    WHERE sa.sqid = subsa.sqid 
    AND sa.hoid = subsa.hoid 
)