Using Mysql IF condition for multiple INSERT - mysql

I would like to use condition in Mysql as below
I have 2 tables- tblPage , tblContent
The SQL should do something in the following order
check if page_name="Home" in tblPage, if false, go to step 2.
Insert some values in tblPage, and get the Last Insert Id.
Insert some values in tbContent with the last Insert Id (of tblPage), and
get the lastInsertId of its own.
Insert some values in tbContent with the lastInsertId (of tbContent), and
get the lastInsertId of its own.
Go on inserting this way.
Step 1 checks to see if any specific value exists in specified column
Step 2 IF the specified value="Home" exist,skip step, If Not, insert some values in tblPage and get the last Insert Id
Step 3 insert some values with the lastInsertId of the previous INSERT in the same table
The step may go on this way inserting some other rows in the same table,with each INSERT getting the
Last Insert Id for the next
I think its posible with MySql IFNULL,NULIF,LAST_INSERT_ID etc, but I cant get it through
I tried with this but the IF condition is still absent.I need to execute the rest of the query if name='home' exists in tblPage
BEGIN
INSERT INTO 'tblPage' ('id','name','url') VALUES
(NULL,'index','home/index');
SET #last_id_in_page = LAST_INSERT_ID();
INSERT INTO 'tblcontent' ('id','page_id','parent') VALUES
(NULL,#last_id_in_page,'home/index');
SET #last_id_in_content = LAST_INSERT_ID();
INSERT INTO 'tblcontent' ('id','page_id','parent') VALUES
(NULL,#last_id_in_page,#last_id_in_content);
SET #last_id_in_content = LAST_INSERT_ID();
INSERT INTO 'tblcontent' ('id','page_id','parent') VALUES
(NULL,#last_id_in_page,#last_id_in_content);
COMMIT;

To get the last inserted id you can use,
$id= mysql_insert_id();
after you insert query and you will get the last inserted id in table .

Related

MySQL - Insert into a table and get the ID of this to insert into another table -- all in one query

I have a exercise_logs table with these columns:
user_id | exercise_name | mood_log_id | weight_log_id | stretch_log_id
I have three tables (mood_logs, weight_logs and stretch_logs) whose primary key is stored in the 3 last three respective columns in exercise_logs.
These are columns my mood_logs table:
id | mood_scale
So I want to create a new mood_logs entry and use the id from that and store that in exercise_log. But I want to do it all in one query.
Here's what I tried so far:
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`)
values('Breathing', 190, (INSERT INTO `mood_logs` (`mood_scale`)
values(9); LAST_INSERT_ID()))
But this does not work.
Is it possible to achieve this in one query?
Thank you so much.
You can try this
First query insert into mood_logs
INSERT INTO `mood_logs` (`mood_scale`)
values(9);
2nd Query insert into exercise_logs
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`)
values('Breathing', 190, (SELECT `mood_scale` FROM `mood_logs` WHERE `mood_scale` = 9))
You first need to INSERT a row into mood_logs.
As the latest inserted id is from the above statement.
You can use last_insert_id() directly within the second insert statement.
INSERT INTO `mood_logs` (`mood_scale`) values (9);
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`) values('Breathing', 190, last_insert_id());
This is assuming you're the only using the database. If someone else uses an INSERT statement before you can use the last_insert_id() then, the id MIGHT be equal to whatever id the latest insert statement.
Can also use variables to store the last_insert_id();
INSERT INTO `mood_logs` (`mood_scale`) values (9);
SET #arbitraryVariableName = last_insert_id();
INSERT INTO `exercise_logs` (`exercise_name`, `user_id`, `mood_log_id`) values('Breathing', 190, #arbitraryVariableName);

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.)

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

MySQL insert - for each row, return insert id

Let's say I have an array of data to insert. I'm going to have an insert that looks like this:
INSERT INTO `table` (`name`, `value`) VALUES('name1','value1'),('name2','value2')
We're assuming that table has a primary key.
Is there a way to, while batch inserting like this, grab the last insert id for each row, and return the those new ids? I know you can't do this traditionally with LAST_INSERT_ID(), but I'm wondering if I could use something like a cursor to achieve this functionality, and maybe a temporary table to store the values until I return them.
Any help would be great.
https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
LAST_INSERT_ID() will return the first id from a multi row insert.
So you can just return that value and:
INSERT INTO `table1` (`name`, `value`) VALUES('name1','value1'),('name2','value2');
SET #firstid := LAST_INSERT_ID();
SELECT * from table1 where id>=#firstid;

insert into after insert into with autonumeric

I have to make two insert into like this:
INSERT INTO CONVERSATION (issue,...) VALUES ('Presentation',...);
INSERT INTO CONVERSATIONMESSAGES VALUES (ConversationId, 'Hello everybody',...);
In the first table the only PK is an autonumeric field (ConversationId) and later I have to know this autonumeric field to insert in the second table.
is there any way to do this? Something like do a select * when Im doing the first Insert to know it for the second Insert?
Thank you very much, I hope I explained correctly.
you could use LAST_INSERT_ID() to insert the last generated autoincremented on the table, eg
INSERT INTO CONVERSATION (issue,...) VALUES ('Presentation',...);
INSERT INTO CONVERSATIONMESSAGES VALUES (LAST_INSERT_ID(), 'Hello everybody',..);
LAST_INSERT_ID()
but this sometimes fail if you have concurrent INSERTs.
Try creating a stored procedure for this,
DELIMITER $$
CREATE PROCEDURE ProcNAME(...PARAMETERS HERE...)
BEGIN
INSERT INTO CONVERSATION (issue,...) VALUES ('Presentation',...);
SET #lstID = (SELECT MAX(ConversationId) FROM CONVERSATION);
INSERT INTO CONVERSATIONMESSAGES VALUES (#lstID, 'Hello..',..);
END
DELIMITER ;
declare #retVal as int
INSERT INTO CONVERSATION (issue,...) VALUES ('Presentation',...);
#retval=SELECT SCOPE_IDENTITY();
INSERT INTO CONVERSATIONMESSAGES VALUES (ConversationId, 'Hello everybody',...);
you will get last inserted row numberic value in #revVal to be used in other table