Mysql query INSERT two tables - mysql

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");

Related

Mysql trigger multiply copies to another table

I have a trigger which copies the inserted data from my table 1 to table 2. I tried inserting 2 data into table 1 and it copies it to my table 2 but the the problem is it copies 2 times the data. Whenever I insert A, B, C into table 1 the value being copied in my table 2 is A, A, A, B, B, B, C, C, C. Please help.
delimiter //
CREATE TRIGGER `copy_table` AFTER INSERT ON table_2
insert into table_1 (id, code, name)
select id, code, name
from table_2;
END;
//
delimiter ;
Your problem is that you are inserting all the data from table_2 into table_1 each time your trigger executes. You need to only insert the new values, which you can do by referring to the NEW pseudo-table:
delimiter //
CREATE TRIGGER `copy_table` AFTER INSERT ON table_2
FOR EACH ROW
BEGIN
INSERT INTO table_1 (id, code, name)
VALUES (NEW.id, NEW.code, NEW.name);
END;
//
delimiter ;
Demo on dbfiddle
Update
If you want the trigger to only insert values if they don't already exist in table_1, you can either
add a UNIQUE index on (id, code, name) to table_1 and use INSERT IGNORE in the trigger; or
Update the trigger to check that the data doesn't exist in the table already:
CREATE TRIGGER `copy_table` AFTER INSERT ON table_2
FOR EACH ROW
BEGIN
IF NOT EXISTS (SELECT *
FROM table_1
WHERE id = NEW.id AND code = NEW.code AND name = NEW.name) THEN
INSERT INTO table_1 (id, code, name) VALUES (NEW.id, NEW.code, NEW.name);
END IF;
END;
Demo on dbfiddle

Copy all data from one table to another via trigger | phpmyadmin

I'm pretty new to this whole trigger thing with PHPMyAdmin. I don't really know what I am doing wrong but I want simply to copy all the data from table1 to table2 like an archive or something like that. Everytime there is an insert it should copy the data to table2.
Table1 has these attributes/fields:
ID
customerID
BookSN(SN = serialnumber)
created_at(when he lend the book)
updated_at(when he gave the book back)
Table2:
Has the same attributes/fields as Table1
I'm trying to solve this:
delimiter //
CREATE TRIGGER `simple_copy` AFTER INSERT ON table1
FOR EACH ROW BEGIN
insert into table2(id, customerID, BookSN, created_at,updated_at)
select ?? -- i dont know what to write here...
from table1;
END;
//
delimiter ;
I would be really grateful if you can help me to fix this total mess.
If there are some data in table1 that you would want to copy in table2 then first run this:
INSERT INTO table2(id, customerID, BookSN, created_at, updated_at)
SELECT id, customerID, BookSN, created_at, updated_at
FROM table1;
Then you can now use a trigger to continuously copy the newly inserted data from table1 into table2.
DELIMITER //
CREATE TRIGGER `simple_copy` AFTER INSERT ON table1
FOR EACH ROW BEGIN
INSERT INTO table2(id, customerID, BookSN, created_at, updated_at)
VALUE (new.id, new.customerID, new.BookSN, new.created_at, new.updated_at);
END//
DELIMITER ;
But if table1 is empty then just go at once with the trigger.
If you want to copy all columns you have to use like this
delimiter #
CREATE TRIGGER `simple_copy` AFTER INSERT ON table1
FOR EACH ROW
BEGIN
insert into table2(id, customerID, BookSN, created_at,updated_at)
values (new.id, new.customerID, new.BookSN, new.created_at,new.updated_at)
from table1;
END#
delimiter ;

Mysql column count doesn't Match value count (but it does!)

I am running the following procedure in mysql:
create procedure addSavingAccount(id int(10), account_number varchar(10))
begin
insert into saving values(id,'savings', account_number, 0);
end //
However, when I try to call it, it gives me this error:
mysql> call addSavingAccount(103, 'B505');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
I checked on anything that could be linked to it, including triggers. But everything seems like it should be working. Here is my list of triggers:
create trigger balance_change_saving after update on saving for each row
begin
if old.balance != new.balance
then
insert into balance_update_history values(null, 'saving', new.account_number, old.balance, new.balance,
(SELECT NOW()), (select USER()));
end if;
end//
create trigger balance_insert_saving after insert on saving for each row
begin
insert into balance_update_history values(null, 'saving', new.account_number, 0, new.balance, (select now()),
(select user()));
end //
create trigger balance_delete_saving after delete on saving for each row
begin
insert into balance_update_history values(null, null, null, old.balance, null,
(SELECT NOW()), (select USER()));
end //
And here is where I define the table:
create table if not exists saving(account_number varchar(10) , customer_id int(10), balance decimal(8,2), primary key(account_number));
I'd just really like to to figure this out.
There are three columns based on your table create statement, not four. (what is the last 0 in that insert?)
Also, in the procedure, it appears that your insert values are out-of-order relative to the table creation order? So you can either rearrange the insert values to match the table, OR specify the columns with the insert.

Retrieving values from an Insert that called a trigger

There are two tables itemsand items_history, after an insert occurs in the itemstable I'm looking to insert an entry into the items_historytable using the below trigger.
I'm a little confused and concerned I'm not doing it correctly, I'm creating two variables NEW.iidand NEW.ip these are both values inserted on the insert that called the trigger. Am I doing it correctly to get the two values and insert them into the items_history table or is there a better more efficient way to do it?
iid on the items_historytable is a FOREIGN KEY of id on the itemstables.
DROP TRIGGER IF EXISTS `item_created_trg`;
CREATE TRIGGER `item_created_trg`
AFTER INSERT ON `items` FOR EACH ROW
BEGIN
SET NEW.iid = (SELECT MAX(id) FROM `items` LIMIT 1);
SET NEW.ip = (SELECT created_ip FROM `items` i WHERE i.id=NEW.iid LIMIT 1);
INSERT INTO `items_history` (iid, title, description, created, created_by, created_ip) VALUES (NEW.iid, 'Added to database.', '', NOW(), 1, NEW.ip);
END;
Thanks in advance.
If I understand you correctly your trigger should look like this
CREATE TRIGGER item_created_trg
AFTER INSERT ON items
FOR EACH ROW
INSERT INTO items_history (iid, title, description, created, created_by, created_ip)
VALUES (NEW.id, 'Added to database.', '', NOW(), 1, NEW.created_ip);
Here is SQLFiddle demo

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