将MySQL查询转换为SQLite

时间:2015-08-20 07:20:58

标签: android mysql sqlite

我得到以下MySQL查询,我需要转换为SQLite查询(在我的Android应用程序中使用)

select *
from msgsList
where (least(msg_from, msg_to), greatest(msg_from, msg_to), msg_time)       
in 
(
    select 
       least(msg_from, msg_to) as x, greatest(msg_from, msg_to) as y, 
       max(msg_time) as msg_time
    from msgsList 
    group by x, y
);

2 个答案:

答案 0 :(得分:1)

在SQLite中,LEAST()/ GREATEST()只是被称为MIN()/ MAX()。

SQLite不支持使用元组的IN,但您可以将表连接到子查询:

SELECT msgsList.*
FROM msgsList
JOIN (SELECT MIN(msg_from, msg_to) AS x,
             MAX(msg_from, msg_to) AS y,
             MAX(msg_time) AS msg_time
     FROM msgsList
     GROUP BY x, y) AS m
ON m.x        = MIN(msgsList.msg_from, msgsList.msg_to) AND
   m.y        = MAX(msgsList.msg_from, msgsList.msg_to) AND
   m.msg_time = msgsList.msg_time;

如果你有SQLite 3.7.11或更高版本(not available in all Android versions),你只需使用聚合MAX()来选择要返回的行:

SELECT *,
       MAX(msg_time)
FROM msgsList
GROUP BY MIN(msg_from, msg_to),
         MAX(msg_from, msg_to);

答案 1 :(得分:-1)

您可以使用SQLiteDatabse类的rawQuery(String query)按原样运行。