简体   繁体   English

连续更新 SQL 表

[英]Update SQL tables consecutively

I have a script that inserts a new user into a table, and the user is defined by the id.我有一个将新用户插入表中的脚本,用户由 id 定义。 I use the id in several other tables to relate certain aspects to that user.我在其他几个表中使用 id 将某些方面与该用户相关联。 For example:例如:

USER TABLE
id | phone number

CATEGORY TABLE
id | userID | cat1 | cat2

TRACKING TABLE
id | userID | track1

In the three tables above, I use the id from USER TABLE to relate that entry to the userID in the two other tables.在上面的三个表中,我使用 USER TABLE 中的 id 将该条目与其他两个表中的 userID 相关联。

I am attempting to take the newest id (max(id)) from USER TABLE to input default values into the other two tables.我试图从 USER TABLE 中获取最新的 id (max(id)) 以将默认值输入到其他两个表中。 For example, when user 3 (id=3, auto_increment) is added to the USER TABLE through an onboarding process from my home page, and SQL script will take the id number and input it into userID in the other two tables as well as default values for cat1, cat2, and track1.例如,当用户 3(id=3,auto_increment)通过我主页的入职流程添加到 USER TABLE 时,SQL 脚本将获取 id 号并将其输入到其他两个表中的 userID 以及默认值cat1、cat2 和 track1 的值。 Is there an efficient way to do this with one query or one block of queries that can be sent at once?有没有一种有效的方法可以通过一个查询或一个可以一次发送的查询块来做到这一点?

Use last_insert_id() :使用last_insert_id()

insert into usertable ( phone ) values ( '12345' );

set @userid = last_insert_id();

insert into category ( userid, cat1, cat2 )
    values (@userid, 'cat1', 'cat2');

insert into tracking ( userid, track1 )
    values (@userid, 'track1');
insert into usertable ( phone ) values ( '12345' );
insert into category ( userid, cat1, cat2 ) select u.id , 'cat1', 'cat2' from usertable u where u.phone='12345';
insert into tracking ( userid, track1 ) select id, 'track1' from usertable u where u.phone='12345';

You should probably place a unique constraint on the phone field of usertable and wrap these query in a transaction so there is no duplication.您可能应该在 usertable 的 phone 字段上放置一个唯一约束,并将这些查询包装在一个事务中,以便没有重复。

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

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