insert into after insert into with autonumeric - mysql

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

Related

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;

Using Mysql IF condition for multiple INSERT

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 .

MySQL Multiplication trigger?

I have a table called history with the fields id, g.id, date, value. I want to put a trigger that will update the table when a new row is inserted and divide the number inserted in the value field by 2.
I have been trying for hours with no luck, any help would be appreciated.
for eg, after
INSERT INTO `online_game_shop`.`history`
(`id`, `gameID`, `dateofPurchase`, `Value`)
VALUES ('1001', '101', '2014-02-22', '10');
so the trigger will automatically divide 10 by 2 and update the field with result.
CREATE TRIGGER pointstovalue
AFTER INSERT ON history
FOR EACH ROW
BEGIN
UPDATE history
SET value = new.value/2
WHERE history.id = NEW.id
END;
You want a before insert trigger:
CREATE TRIGGER pointstovalue
BEFORE INSERT ON history
FOR EACH ROW
BEGIN
set new.value = new.value/2;
END;

Mysql Trigger to insert the last date

I have to make only one insertion / day on a Mysql table .
DELIMITER $$
CREATE TRIGGER trig
BEFORE INSERT ON Table
FOR EACH ROW BEGIN
/** compare the date with the latest inserted **/
IF () THEN
// if it's ok => insert
ELSE
// nothing
END IF;
END$$
DELIMITER ;
I want to compare the last inserted date and current date and then initiate my trigger to do the work.
Thanks
You can achieve this without trigger (which is a good thing right?) by creating a UNIQUE constraint on the date column and then using INSERT IGNORE syntax.
Suppose you have a table with the following schema
CREATE TABLE table1
(
date DATE,
value INT
);
Let's create a UNIQUE constraint
CREATE UNIQUE INDEX idx_date_unique ON table1 (date);
Now you can use IGNORE clause
INSERT IGNORE INTO table1 VALUES (CURDATE(), 1);
INSERT IGNORE INTO table1 VALUES (CURDATE(), 2);
INSERT IGNORE INTO table1 VALUES (CURDATE(), 3);
As a result you'll have only first row in the table for each day.
Here is SQLFiddle demo

Mysql query INSERT two tables

I have two tables:table1 and rating
table1(id,name,category)
rating (cid,rating,total_rating,total_rates,photoID)
and now when i insert data into table1 i want to set all data in table rating at zero for that specific photoID from table1, but i dont know how..can someone help me?
You can use LAST_INSERT_ID() to retrieve the ID you just inserted. For example, assuming PhotoID is the relation between table1 and rating:
insert table1 (name,category) values ('waterfall 2', 'nature');
insert rating (rating,total_rating,total_rates,photoID) values
(0, 0, 0, last_insert_id());
I'd rather create a STORED PROCEDURE to make a single call from application. Assuming that you want to INSERT a record on table rating for every insert on table1 and that ID on table1 is set as AUTO_INCREMENT.
DELIMITER $$
CREATE PROCEDURE procedureName
(
IN _name VARCHAR(25),
IN _category VARCHAR(25)
)
BEGIN
INSERT INTO table1 (name, category)
VALUES (_name, _category);
SET #last_ID := LAST_INSERT_ID();
INSERT INTO rating (cid, rating, total_rating, total_rates, photoID)
VALUES (#last_ID, 0,0,0,0);
END $$
DELIMITER ;
and call the procedure,
CALL procedureName('nameHere','categoryHere')
You can use MySql triggers http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html:
CREATE TRIGGER ins_rating AFTER INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO rating (cid,rating,total_rating,total_rates,photoID)
VALUES( NEW.ID ,0,0,0,null)
END;
If you want to insert data into TABLE1 and delete it from TABLE2, you can write below listed query:
mysql_query("DELETE * FROM table2");