在 View 中连接两个表时sqlite3日期操作?

标签 sql database datetime sqlite

简而言之,如何在 sqlite3 中通过连接它们,在一个 select 语句中将来自另一个表中的整数的分钟添加到日期时间?

我有一个 sqlite3 数据库:

表 P(int id, ..., int 分钟) 和一个表 S(int id, int p_id, datetime start)

我想生成一个 View ,通过加入 S.p_id=P.id 为我提供 PS(S.id, P.id, S.start + P.minutes)

问题是,如果我从应用程序生成查询,我可以执行以下操作:

select datetime('2010-04-21 14:00', '+20 minutes');
2010-04-21 14:20:00

通过在应用程序中创建字符串“+20 分钟”,然后将其传递给 sqlite。但是我找不到在选择本身中创建此字符串的方法:

select p.*,datetime(s.start_at, formatstring('+%s minutes', p.minutes)) from p,s where s.p_id=p.id;

因为据文档所述,sqlite 不提供任何字符串格式函数,我也看不到任何表达日期修饰符的替代方法。

在 MySQL 中,日期修饰符不是基于字符串的,因此它实际上是有效的:

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)

最佳答案

使用 + 无法进行串联。然而||串联操作数确实按预期工作。

所以MySQL的

SELECT p.*,(s.start + INTERVAL p.minutes MINUTE) FROM p,s WHERE p.id=s.p_id;

可以在sqlite3中写成:

select p.*, datetime(s.start, '+' || p.minutes || ' minutes') from p, s where s.p_id=p.id;

这会产生正确的答案。感谢 newtover 指出了正确的方向。

1|10|2008-12-31 14:10:00
1|10|2008-12-31 15:10:00
2|15|2008-05-10 13:45:00

关于在 View 中连接两个表时sqlite3日期操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2751063/

相关文章:

java - 在 Freemarker 中打印日期天数差异时出错

mysql - 按升序获取表中的字母数字值

c# - 使用 System.Data.Linq.Mapping 并自动递增 sqlite 数据库中的主键时出错

sql - 从表中获取 TIME 数据类型 (MSSQL08) 的 SUM

sql - 数据库安全问题

database - 迁移中的 Laravel 关系?

javascript - 从 Javascript 发布到 ASP.NET 中的 Controller 的 DateTime 结果为 null (01/01/0001)

带有本地(内联)数组的 SQL 语句

sql - 可以组合日期和时间并存储为日期时间格式

python - django: 'tuple' 对象没有属性 'strftime'