简体   繁体   English

sqlite3 插入联合 SELECT

[英]sqlite3 INSERT INTO UNION SELECT

INSERT INTO table1
    SELECT "hello" AS field1, 15 AS field2, 1262340000 AS timestamp 
    UNION 
    SELECT "byebye", 10, 1262340000 
    UNION 
    SELECT "hi", 20, 1262340000 
    UNION 
    SELECT "boo", 25, 1262340000 

Table columns:表列:

field1  field2  timestamp   pk

pk is the auto-incrementing primary key pk是自增主键

An error occurs when I execute this SQL当我执行这个 SQL 时出现错误

DB Error: 1 "table table1 has 4 columns but 3 values were supplied"数据库错误:1“表 table1 有 4 列,但提供了 3 个值”

You should explicitly specify which columns in table1 your insert is targeting:您应该明确指定table1中的哪些列是您插入的目标:

INSERT INTO table1 (field1, field2, timestamp)
SELECT 'hello', 15, 1262340000
UNION ALL
SELECT 'byebye', 10, 1262340000
UNION ALL
SELECT 'hi', 20, 1262340000
UNION ALL
SELECT 'boo', 25, 1262340000;

When you omit the select list entirely, SQLite will fall back to expecting values for all columns in the table, in the exact order specified by the table definition.当您完全省略 select 列表时,SQLite 将退回到表中所有列的期望值,按照表定义指定的确切顺序。 In your case, as you only provided values for 3 out of the 4 total columns, you get an error.在您的情况下,由于您只提供了 4 列中的 3 列的值,因此您会收到错误消息。 Note that you could have also used VALUES here:请注意,您也可以在此处使用VALUES

INSERT INTO table1 (field1, field2, timestamp)
VALUES
    ('hello',  15, 1262340000),
    ('byebye', 10, 1262340000),
    ('hi',     20, 1262340000),
    ('boo',    25, 1262340000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM