将查询从MySql转换为Sqlite

时间:2014-05-04 22:53:14

标签: mysql sql sqlite

我需要将此查询从MySQL格式转换为SQLite。我正在努力,但我发现了一些困难。

在SQLite中,curdate()和interval函数不存在。

select a.Date 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date between '2010-01-20' and '2010-01-24' 

2 个答案:

答案 0 :(得分:2)

这个查询实际上做的只是生成大量连续日期(前几天最多一千天)。

在SQLite 3.8.3或更高版本中,使用递归common table expression可以更轻松地完成此操作:

WITH RECURSIVE dates(d)
AS (VALUES('2010-01-20')
    UNION ALL
    SELECT date(d, '+1 day')
    FROM dates
    WHERE d < '2010-01-24')
SELECT d AS date FROM dates;

答案 1 :(得分:1)

以下是基本语法:

select a.Date 
from (select date('now', '-'||(a.a + (10 * b.a) + (100 * c.a))|| ' days') as Date
      from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9
           ) a cross join
           (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9
           ) b cross join
           (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9
           ) c
    ) a;

我遗漏了where条款,因为这些日期过去超过1000天,所以他们不会选择任何东西。