Mysql 两个SQL插入相互依赖';结果。。。什么';什么是最好的方法?
我有一个库存表(针对零售店的产品/库存)和一个序列表(针对每种库存发布的条形码) 基本上,当新股票被引入数据库时,系统会为每只股票发布一个序列号。。。基于serials表的index/pri自动增量值 问题是他们都是相互依赖的 我会解释:Mysql 两个SQL插入相互依赖';结果。。。什么';什么是最好的方法?,mysql,Mysql,我有一个库存表(针对零售店的产品/库存)和一个序列表(针对每种库存发布的条形码) 基本上,当新股票被引入数据库时,系统会为每只股票发布一个序列号。。。基于serials表的index/pri自动增量值 问题是他们都是相互依赖的 我会解释: STOCKS TABLE stock_id int(11) product_name varchar(50) serial int(30) <--- relies on the serials generated by system, stored i
STOCKS TABLE
stock_id int(11)
product_name varchar(50)
serial int(30) <--- relies on the serials generated by system, stored in the SERIALS TABLE
SERIALS
sn_id int(11)
stock_id int(11) <-- relies on the new stocks inserted in the stocks table
serial int(30) <---- serial NO generated for specific stock.
我的原始版本实际上已经对serials表进行了插入,然后在生成stock_id之后对serials表进行更新。。由于另一条SQL语句的发布,我对此感到不舒服,尽管这是最安全的方法,而且我不需要担心锁文件和冲突 嗯。。有什么想法吗 编辑:
我决定改变我的方法。
对于生成的每个序列,都有一个库存(库存id)。。我决定忘记序列号00001 0002 0003的增量排序 决定继续使用发行序列号的特定股票的股票id 所以..
获取下一个插入id,根据该id生成序列号,
插入库存,带生成序列号
插入序列记录,同时将库存id引用到相同的下一个插入id 完成了
我真的很想有一个完美的序列号..不要创建锁文件-这是错误的 相反,请使用事务。以下是Perl中的示例:
my $dbh = DBI->connect("dbi:mysql...", "user", "password");
$dbh->begin_work(); # start new transaction
$dbh->do("INSERT INTO serials ..."); # generate new serial
my $new_serial = $dbh->{mysql_insertid};
$dbh->do("INSERT INTO stocks (..., serialno) VALUES (..., $new_serial)");
# do some more work like inserting into other tables
$dbh->commit(); # finally, commit the transaction
请注意,您需要使用InnoDB引擎进行事务处理ah谢谢。。我知道你的密码。。我实际上在使用事务处理。。但是我希望我的序列以序列的形式生成,每个序列的序列号id,没有跳过。。回滚的事务将在序列中留下间隙。如果两个或多个并行事务开始并获取很少的串行ID,但其中一个回滚,则无法避免出现间隙。所以,不要太担心差距——你无法通过事务来避免它们。。我同意。。我要放弃我的强迫性然后lolz非常感谢
my $dbh = DBI->connect("dbi:mysql...", "user", "password");
$dbh->begin_work(); # start new transaction
$dbh->do("INSERT INTO serials ..."); # generate new serial
my $new_serial = $dbh->{mysql_insertid};
$dbh->do("INSERT INTO stocks (..., serialno) VALUES (..., $new_serial)");
# do some more work like inserting into other tables
$dbh->commit(); # finally, commit the transaction