如何使用新列更新SQLite表?

时间:2016-12-24 21:14:46

标签: sql sqlite

在sqlite中,我的表格如下:

---------------------
Date           Temp
---------------------
201309010051    82
201309010151    81
201309010251    80
---------------------

我生成如下查询,修改日期时间格式,从201309010051到2013-09-01 00:51。

以下是我用来对“'日期”中的所有值执行此操作的查询。专栏:

select substr(Date, 1, 4)||"-"||substr(Date, 5, 2)||"-"||substr(Date, 7, 2) 
||" "||substr(Date, 9, 2)||":"||substr(Date, 11, 2) as CreatedColumn  
from myTable

现在,我想添加' CreatedColumn'到我原来的桌子。我尝试了以下方法:

update myTable set CreatedColumn = <my above query which modifies the datetime format>

但是,它会返回以下错误:

(sqlite3.OperationalError) near "select": syntax error

如何添加/附加&#39; CreatedColumn&#39;从我的查询到原始表生成?

2 个答案:

答案 0 :(得分:3)

@Dekel写的查询对于插入数据是正确的。在向新列添加信息之前,必须首先创建它。

- 初始创建表格和插入数据:

DROP TABLE IF EXISTS `myTable`; 
CREATE TABLE `myTable`(
    `Date` int, 
    `Temp` int
); 

INSERT INTO `myTable` VALUES (201309010051,82),
                             (201309010151,81),
                             (201309010251,80);

- SELECT *:

SELECT * FROM `myTable`;
+------------+------+
| Date       | Temp |
+------------+------+
| 2147483647 |   82 |
| 2147483647 |   81 |
| 2147483647 |   80 |
+------------+------+
3 rows in set (0.00 sec)

- 更改表格

ALTER TABLE `myTable` ADD COLUMN `CreatedColumn` DATETIME; 

SELECT * FROM `myTable`;
    +------------+------+---------------+
    | Date       | Temp | CreatedColumn |
    +------------+------+---------------+
    | 2147483647 |   82 | NULL          |
    | 2147483647 |   81 | NULL          |
    | 2147483647 |   80 | NULL          |
    +------------+------+---------------+
    3 rows in set (0.00 sec)

- 更新CreatedColumn - 使用Dekel的命令

UPDATE
    `myTable` 
SET 
    `CreatedColumn` = substr(Date, 1, 4)||"-"||substr(Date, 5, 2)||"-"||substr(Date, 7, 2) ||" "||substr(Date, 9, 2)||":"||substr(Date, 11, 2);

- 显示对表的更改

SELECT * FROM `myTable`; 
    +------------+------+---------------------+
    | Date       | Temp | CreatedColumn       |
    +------------+------+---------------------+
    | 2147483647 |   82 | 0000-00-00 00:00:00 |
    | 2147483647 |   81 | 0000-00-00 00:00:00 |
    | 2147483647 |   80 | 0000-00-00 00:00:00 |
    +------------+------+---------------------+
    3 rows in set (0.00 sec)

答案 1 :(得分:2)

如果您已经有列CreatedColumn,则可以使用以下查询为每行设置列的值:

UPDATE
    myTable 
SET 
    CreatedColumn = substr(Date, 1, 4)||"-"||substr(Date, 5, 2)||"-"||substr(Date, 7, 2) ||" "||substr(Date, 9, 2)||":"||substr(Date, 11, 2)