Sqlite3 date operations when joining two tables in a view?
Long story short, how can I add minutes to a datetime from an integer located in another table in one of the select statements by concatenating them in sqlite3?
I have sqlite3 db with:
table P (int id, ..., int minutes) and table S (int id, int p_id, start datetime)
I want to create a view that gives me PS (S.id, P.id, S.start + P.minutes) by joining S.p_id = P.id
The problem is that if I create a request from the application, I can do things like:
select datetime('2010-04-21 14:00', '+20 minutes');
2010-04-21 14:20:00
By creating the string "+20 minutes" in the application, and then passing it to sqlite. However, I cannot find a way to create this line in the select itself:
select p.*,datetime(s.start_at, formatstring('+%s minutes', p.minutes)) from p,s where s.p_id=p.id;
Since sqlite, as the documentation says, does not provide any string format function, and I see no alternative way to express date modifiers.
In MySQL, date modifiers are not string-based, so it actually works:
mysql> create table p ( id integer, minutes integer);
mysql> create table s ( id integer, p_id integer, start datetime);
mysql> insert into p values (1, 10);
mysql> insert into p values (2, 15);
mysql> insert into s values (1, 1, '2008-12-31 14:00');
mysql> insert into s values (2, 1, '2008-12-31 15:00');
mysql> insert into s values (3, 2, '2008-05-10 13:30');
mysql> SELECT p.*,(s.start + INTERVAL p.minutes MINUTE) FROM p,s WHERE p.id=s.p_id;
+------+---------+---------------------------------------+
| id | minutes | (s.start + INTERVAL p.minutes MINUTE) |
+------+---------+---------------------------------------+
| 1 | 10 | 2008-12-31 14:10:00 |
| 1 | 10 | 2008-12-31 15:10:00 |
| 2 | 15 | 2008-05-10 13:45:00 |
+------+---------+---------------------------------------+
3 rows in set (0.02 sec)
a source to share
Concatenation didn't work using +. However || the concatenation operand worked as expected.
So MySQL
SELECT p.*,(s.start + INTERVAL p.minutes MINUTE) FROM p,s WHERE p.id=s.p_id;
Can be written in sqlite3 as:
select p.*, datetime(s.start, '+' || p.minutes || ' minutes') from p, s where s.p_id=p.id;
Which gives the correct answer. Thanks to newtover for pointing in the right direction.
1|10|2008-12-31 14:10:00
1|10|2008-12-31 15:10:00
2|15|2008-05-10 13:45:00
a source to share