简体   繁体   中英

Submit multiple queries same time mysql inserting same id twice

Want to submit auto-increment value of table_a into table_b at same time. I first inserting record into table_a and then fetching last primary id from table_a and inserting it into table_b . It works well at slow speed like 20 records per sec, but a fast speed and multi user level it inserting duplicate id of table_a into table_b .

在此输入图像描述

Is my approach is wrong ? Please suggest better way to do this.

code

query1 = "insert into `table_a` (`aid`,`name`) values(null,'val')";

query2 = "select `id` from `table_a` order by `id` desc limit 1";

$aid='retrieved_value';

query3 = "insert into table_b (`bid`,`aid`,`btype`) values (null,'$aid','val')";

Yes, your approach is wrong. It is very racy. You have no guarantee that query2 returns the id related to query1 . A better approach is to use the last_insert_id function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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