group_concat sqlite和order by

时间:2013-02-20 00:31:15

标签: sqlite group-concat sql-order-by

我正在尝试在sqlite3中的group_concat中订购。这种方式不支持mysql,所以我不能这样做:

group_concat(logID order by logDateTime DESC)

我的完整查询在这里,我需要logID由logDateTime订购。我在这里阅读了一个子查询方法:Sqlite group_concat ordering但我无法在查询中使用它。

SELECT logID,
       NULL AS sessionID,
       logDateTime,
       NULL AS sessionName,
       NULL AS NamesInRandomOrder
FROM logs
WHERE sessionID IS NULL

UNION ALL

SELECT NULL,
       sessions.sessionID,
       MAX(logDateTime),
       sessions.sessionName,
       group_concat(logID)
FROM logs
JOIN sessions ON logs.sessionID = sessions.sessionID
GROUP BY sessions.sessionID

ORDER BY 3 DESC

1 个答案:

答案 0 :(得分:0)

这命令子查询,但SQLite不保证订单在所有情况下都保留:

SELECT logID,
       NULL AS sessionID,
       logDateTime,
       logName,
       NULL AS NamesInRandomOrder
FROM logs
WHERE sessionID IS NULL

UNION ALL

SELECT NULL,
       sessionID,
       MAX(logDateTime),
       sessionName,
       group_concat(logName)
FROM (SELECT sessions.sessionID AS sessionID,
             logDateTime,
             sessionName,
             logName
      FROM logs JOIN sessions ON logs.sessionID = sessions.sessionID
      ORDER BY sessions.sessionID,
               logName)
GROUP BY sessionID

ORDER BY 3 DESC