简体   繁体   English

从 SQLite INSERT INTO 操作中检索值

[英]Retrieve a value from a SQLite INSERT INTO operation

I am building an SQL database with SQLite3 and the Haskell library HDBC to connect to the database from my program.我正在使用 SQLite3 和 Haskell 库 HDBC 构建 SQL 数据库,以从我的程序连接到数据库。 It's used for tracking sales of products (ie. on an EPOS).它用于跟踪产品的销售(即在 EPOS 上)。 The schema is roughly like this, amended for brevity:架构大致是这样的,为简洁起见进行了修改:

create table products (
    product_id    integer primary key autoincrement,
    product_name  text,
    product_price integer
);

create table sales (
    sales_id    integer primary key auto increment
    sales_date  date,
    number_sold integer
);

create table products_sales_xref (
    product_id integer references products,
    sales_id   integer primary key references sales
);

I want to insert a value into sales (ie, when a sale is logged/made) and then be able to take the value of the auto-incremented sales_id and use that in an insert into the cross-referencing table.我想在销售中插入一个值(即,当记录/进行销售时),然后能够获取自动递增的sales_id的值并将其用于插入到交叉引用表中。 I tried something like:我试过类似的东西:

INSERT INTO products_sales_xref (product_id, sales_id) VALUES (2, 
  (INSERT INTO sales (sales_date, number_sold)
     VALUES ('2022-08-05', 25) RETURNING sales_id)
);
-- or
INSERT INTO products_sales_xref (product_id, sales_id)
SELECT 2, * from (
  INSERT INTO sales (sales_date, number_sold) VALUES ('2022-08-05', 25) RETURNING sales_id
);

which fails because of a parse error: Parse error: near "INSERT": syntax error .由于解析错误而失败: Parse error: near "INSERT": syntax error It seems like I can't use INSERT in a subquery?好像我不能在子查询中使用 INSERT? Is there a way I can use this value in the xref insert statement?有没有办法可以在外部参照插入语句中使用这个值? I'd rather not use the get_last_rowid in case of a new value somehow getting in between the first insert and the second one.如果新值以某种方式进入第一个插入和第二个插入之间,我宁愿不使用 get_last_rowid 。

One statement can INSERT into ONE table!一条语句可以插入到一张表中!

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

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