gpt4 book ai didi

sql - 表 A 引用表 B,我如何插入(使用 Perl 和 DBI 以及 PostgreSQL)

转载 作者:行者123 更新时间:2023-11-29 12:47:23 25 4
gpt4 key购买 nike

考虑表 A 引用表 B 的情况:

create table tableA
(
id INT NOT NULL PRIMARY KEY,
information VARCHAR(32)
);
create table tableB
(
id INT NOT NULL PRIMARY KEY,
tableAid INT NOT NULL REFERENCES tableA(id),
other_information VARCHAR(32)
):

请注意,我正在用 Perl 编写代码,数据库是 PostgreSQL。

因此,我有 2 个 tableB 条目绑定(bind)到单个 tableA 条目。我想说这样的话:

use DBI;
my $dbh = DBI->connect("DBI:Pg:dbname=mydb;host=localhost","userid","password",('RaiseError' -> 1));

my $otherinfo = "other info, Table B";
my $moreotherinfo = "more other info, table B";
my info = "table A info";
my $insertitA = $dbh->prepare("insert into tableA (information) values (?)");
my $insertitB = $dbh->prepare("insert into tableB (tableAid,other_information) values (?,?)");
my $nrowsA = $insertitA($info);
my $tableAidreference = ????;
my $nrowsB = $insertitB($tableAidreference, $otherinfo);
my $nrowsB2 = $insertitB($tableAidreference, $moreotherinfo);

我从哪里得到 $tableAidreference?我必须搜索 tableA 吗?

最佳答案

为后续 INSERT 单独调用 nextval('seq_name') 的方法已经过时且效率非常低。它需要额外的往返服务器。不要用这个。有更好的选择:

-> sqlfiddle

首先,我修改了您的测试设置:

CREATE TABLE tbl_a
( tbl_a_id serial NOT NULL PRIMARY KEY,
information text
);
CREATE TABLE tbl_b
( tbl_b_id serial NOT NULL PRIMARY KEY,
tbl_a_id int NOT NULL REFERENCES tbl_a(tbl_a_id),
other_information text
);
  • 不要使用 id 作为列名,它不是描述性的。一些不太聪明的 ORM 会这样做,这是一种反模式。

  • 如果可以避免的话,不要在 PostgreSQL 中使用大小写混合的标识符。

  • 使用 serial代理主键的类型。

然后,一次完成所有操作 data-modifying CTE (需要 PostgreSQL 9.1 或更高版本)使用 INSERTRETURNING 子句命令:

WITH x AS (
INSERT INTO tbl_a (information)
VALUES ('foo')
RETURNING tbl_a_id
)
INSERT INTO tbl_b (tbl_a_id, other_information)
SELECT tbl_a_id, 'bar'
FROM x
RETURNING tbl_a_id, tbl_b_id; -- optional, if you want IDs back

一次 往返服务器,如果需要,您可以取回两个新 ID,而不是三次 往返。


如何将其与 DBI 一起使用?

使用 DBD::Pg 模块:

$SQL = q{ WITH x AS (
INSERT INTO tbl_a (information)
VALUES (?)
RETURNING tbl_a_id
)
INSERT INTO tbl_b (tbl_a_id, other_information)
SELECT tbl_a_id, 'bar'
FROM x
RETURNING tbl_a_id, tbl_b_id};
$answer = $dbh->prepare($SQL);
$sth->execute('foo');
$tbl_a_id = $answer->fetch()->[0];
$tbl_b_id = $answer->fetch()->[1];

未经测试。有一个完整的example how to do it in the DBD::Pg manual .

关于sql - 表 A 引用表 B,我如何插入(使用 Perl 和 DBI 以及 PostgreSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com