- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set different auto-increment ids for two tables with a user-defined variable?
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)
- Related Articles
- MongoDB query to set user defined variable into query?
- Set user-defined variable with table name in MySQL prepare statement?
- Select into a user-defined variable with MySQL
- MySQL ORDER BY with numeric user-defined variable?
- Set custom Auto Increment with ZEROFILL in MySQL
- Increment multiple Timestamp values by setting the incremented value in a user-defined variable in SQL
- C++ set for user defined data type?
- How to auto-increment value of tables to lower value in MySQL?
- How Can we permanently define user-defined variable for a client in MySQL?
- Set different IDs for records with conditions using a single MySQL query
- Set custom messages by working with MySQL IF Statements and SELECT in a user-defined variable
- How can we store a value in user-defined variable?
- How to set initial value and auto increment in MySQL?
- Swap two Strings without using third user defined variable in Java
- Auto increment in MongoDB to store sequence of Unique User ID?

Advertisements