INSERT and then SELECT the inserted row - mysql

My table Structure,Table Name- user_tb
User_Id Name Mob_No City
=================================
100 Sumith 34542 dfsc
101 Yadhu 35485 dfgd
102 Aby 34234 jhhg
Here column User_Id is auto_increment
and am inserting values to this table using this query,
insert into user_tb(Name,Mob_No,City) values('Yadhu',34542,'dfsc');
I need to get User_Id of the Person at the time of insertion
ie, when am inserting using this query,
insert into user_tb(Name,Mob_No,City) values('Yadhu',34542,'dfsc');
i need to get User_id-101
Is this possible....
Anyone please help me to complete this.

Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT, use a SELECT query with the LAST_INSERT_ID() function.
For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.
insert into user_tb(Name,Mob_No,City) values('Yadhu',34542,'dfsc');
SELECT LAST_INSERT_ID();
If you do not require the value within your application, but do require the value as part of another INSERT, the entire process can be handled by executing the following statements:
insert into user_tb(Name,Mob_No,City) values ('Yadhu',34542,'dfsc');
insert into tbl2 (id,text) VALUES (LAST_INSERT_ID(),'text');

In Mysql: use LAST_INSERT_ID() function; http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html
If PHP: use mysql_insert_id() to get the last id inserted by your query.
http://php.net/manual/en/function.mysql-insert-id.php

Related

get the last ID after insert in mysql

how can i get the ID of the last insert statement
im using trigger to create a ID for every record
INSERT INTO table1_seqdocument VALUES (NULL);
SET NEW.tracknum = CONCAT('DOC', LPAD(LAST_INSERT_ID(), 3, '0'));
and i need that ID for other table
this is this my insert statement
INSERT INTO tble_transaction
(
tracknum
,signatoryid
,signed
,status
,signatorylevel
)
VALUES
(?,?,?,?,? )
what i want is to retrieve the ID and use it for another insert statement but using other table. is it possible? thank you
You can use ##identity
SELECT ##IDENTITY AS [##IDENTITY];
LAST_INSERT_ID() can only tell you the ID of the most recently auto-generated ID for that entire database connection, not for each individual table, which is also why the query should only read SELECT LAST_INSERT_ID() - without specifying a table. As soon as you fire off another INSERT query on that connection, it gets overwritten. If you want the generated ID when you insert to some table, you must run SELECT LAST_INSERT_ID() immediately after doing that (or use some API function which does this for you).
If you want the newest ID currently in an arbitrary table, you have to do a SELECT MAX(id) on that table, where id is the name of your ID column. However, this is not necessarily the most recently generated ID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform an INSERT between your own INSERT and your selection of the ID.
(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in table1.)

Database INSERT INTO SET ... WHERE(SELECT ...)

I am trying to insert my values into table if Admin_User_Role_Id value against Admin_Id is not present in the table. Is it possible to insert!
My Table Structure:
Admin_User_Id (FK)
Admin_User_Role_Id (FK)
Is_Enabled (boolean flag)
Query which I tried, but not success
INSERT INTO role_association
SET Admin_User_Id=61, Admin_User_Role_Id=2, Is_Enabled=0
WHERE Admin_User_Role_Id
NOT IN
(SELECT Admin_User_Id, Admin_User_Role_Id FROM role_association)
I think it is possible but my logic is wrong. How should I manage this query to work successfully!
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
Probably you take care about where condition in your programming logic and write a simple insert statement and the depending on your logic use this statement to insert the records. Hope you got my point.
You want to insert your values in your table using this query for your reference
INSERT INTO Yourtablename(column1,column2,column3,...)
VALUES ('value1','value2','value3',.....);
You want to ADD one new column in your table means using this query
** ALTER TABLE table_name ADD column_name datatype**

Can you combine INSERT INTO and Last_Insert_ID in one SQL Statement

I'm need to get the ID of the last record inserted into my table.
INSERT INTO mytable (Column1, Column2) VALUE ('Test', 'Bob');
SELECT/SET LAST_INSERT_ID() as NewID;
Response.Write rst("NewID") '(for example)
Can it run in one statement, or do I need to run the SELECT LAST_INSERT_ID after the INSERT SQL has ran.
I am using MYSQL and ASP
You need to run it after every statment as it will always returns one id of most recent inserted record.
To achieve your goal,
You need to do is, whenever any record inserted to table, get the last id and store it in to any string/table every time and return it from your sproc. This way you get all inserted id at once.
I think that you need to run 2 procedure, first insert and then select order by id desc

Trouble with MAX(col)+1 INSERT into same MySQL table

I need two id columns in the same table that create unique values upon insert. Since MySQL allows only one column to auto-increment, I need to do something like max(id)+1 for the other column.
Here's the SQL I expected to work:
INSERT INTO invoices (invoiceid)
VALUES ((SELECT MAX(invoiceid)+1 FROM invoices))
The select statement works independently, but within my INSERT, it's not allowed. I get the error : You can't specify target table 'invoices' for update in FROM clause
You want to use INSERT INTO .... SELECT FROM instead of INSERT INTO...VALUES():
INSERT INTO invoices (invoiceid)
SELECT MAX(invoiceid)+1
FROM invoices
My question for you would be why are you not use an AUTO INCREMENT field to generate the invoiceid value? That is what it is for, then you will not have to create this when inserting data.

MySQL LAST_INSERT_ID() used with multiple records INSERT statement

If I insert multiple records with a loop that executes a single record insert, the last insert id returned is, as expected, the last one. But if I do a multiple records insert statement:
INSERT INTO people (name,age)
VALUES ('William',25), ('Bart',15), ('Mary',12);
Let's say the three above are the first records inserted in the table. After the insert statement I expected the last insert id to return 3, but it returned 1. The first insert id for the statement in question.
So can someone please confirm if this is the normal behavior of LAST_INSERT_ID() in the context of multiple records INSERT statements. So I can base my code on it.
Yes. This behavior of last_insert_id() is documented in the MySQL docs:
Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.
This behavior is mentioned on the man page for MySQL. It's in the comments but is not challenged, so I'm guessing it's the expected behavior.
I think it's possible if your table has unique autoincrement column (ID) and you don't require them to be returned by mysql itself. I would cost you 3 more DB requests and some processing. It would require these steps:
Get "Before MAX(ID)" right before your insert:
SELECT MAX(id) AS before_max_id FROM table_name`
Make multiple INSERT ... VALUES () query with your data and keep them:
INSERT INTO table_name
(col1, col2)
VALUES
("value1-1" , "value1-2"),
("value2-1" , "value2-2"),
("value3-1" , "value3-2"),
ON DUPLICATE KEY UPDATE
Get "After MAX(ID)" right after your insert:
SELECT MAX(id) AS after_max_id FROM table_name`
Get records with IDs between "Before MAX(ID)" and "After MAX(ID)" including:
SELECT * FROM table_name WHERE id>$before_max_id AND id<=$after_max_id`
Do a check of retrieved data with data you inserted to match them and remove any records that were not inserted by you. The remaining records have your IDs:
foreach ($after_collection as $after_item) {
foreach ($input_collection as $input_item) {
if ( $after_item->compare_content($input_item) ) {
$intersection_array[] = $after_item;
}
}
}
This is just how a common person would solve it in a real world, with parts of code. Thanks to autoincrement it should get smallest possible amount of records to check against, so they will not take lot of processing. This is not the final "copy & paste" code - eg. you have to create your own function compare_content() according you your needs.