How to set different auto-increment ids for two tables with a user-defined variable?

MySQLMySQLi Database

For this, you can use LAST_INSERT_ID(). Let us first create a table. Here, we have set the auto_increment id to StudentId column −

mysql> create table DemoTable1 (StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY);
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(null);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
|         1 |
+-----------+
1 row in set (0.00 sec)

Following is the query to get last insert id. We have set it in a user-defined variable −

mysql> set @studentId=last_insert_id();
Query OK, 0 rows affected (0.00 sec)

Following is the query to create second table −

mysql> create table DemoTable2 (Id int);
Query OK, 0 rows affected (0.61 sec)

Following is the query to set different auto-increment ids for two tables −

mysql> insert into DemoTable2 values(@studentId+1);
Query OK, 1 row affected (0.13 sec)

Display all records from the table with the help of select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+------+
| Id   |
+------+
|    2 |
+------+
1 row in set (0.00 sec)
raja
Published on 22-Aug-2019 14:55:48
Advertisements