I have a table named clients, in that table there's two columns of importance; id and client. I have a secondary table in the same database named calendar. I really want the two columns of id and client in the calendar table to sync with the ones in client table.
Right now I am using this PHP to execute this in MySQL:
INSERT IGNORE INTO calendar (id, client) SELECT id, client FROM clients;
Is there a better way of accomplish this task? Maybe a built in function in MySQL that I have overlooked or something like that?
Use Triggers : The MySQL trigger is a database object that is associated with a table. It will be activated when a defined action is executed for the table.
The trigger can be executed when you run one of the following MySQL statements on the table: INSERT, UPDATE and DELETE and it can be invoked before or after the event.
You can make trigger when you insert or update a row in main table and make the changes in another table
Example:
DELIMITER $$
CREATE TRIGGER my_sync_trigger
AFTER INSERT ON `clients` for each row
begin
INSERT INTO calender (id,client)
Values (new.id, new.client);
END$$
DELIMITER ;
"new" stands for the new value inserted into clients table. The same value will be inserted into id and client column in calender.
Note: single quotes are removed from table name because quotes effectively make it a string literal instead of a proper identifier.
DELIMITER command will change the ending of each statement from ";" to "$$" so that MySQL is not confused with ";" inside and outside the trigger
Make similar triggers for update and delete also
Simple guide for examples and syntax:
http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx
Related
I am quite new to SQL and am working on a small project, but I got stuck when wanting to implement triggers to my model.
I am designing a database for a sports league. I have a table "GamePlayed" with a column called "GoalsScored" and another one "Team" with a column called "GoalsFor". Those two tables are connected by the "TeamID" key.
I would like to have a trigger that updates the value of "GoalsFor" by adding to the previous value the value of "GoalsScored". In this way, with every game, the total quantity of goals scored will be constantly updated.
I tried the following:
CREATE TRIGGER "Goalsscored" AFTER UPDATE
ON `GamePlayed`
FOR EACH ROW
BEGIN
UPDATE `Team` SET `Team`.`GoalsFor`=`Team`.`GoalsFor`+`GamePlayed`.`GoalsScored`
WHERE `GamePlayed`.`Team_TeamID`=`Team`.`TeamID`
END
Unfortunately, it says there is a problem in my SQL syntax...
How can I do it?
You need to change your delimiter. Something like this
delimiter $$
CREATE TRIGGER "Goalsscored" AFTER UPDATE
ON `GamePlayed`
FOR EACH ROW
BEGIN
UPDATE `Team` SET `Team`.`GoalsFor`=`Team`.`GoalsFor`+`GamePlayed`.`GoalsScored`
WHERE `GamePlayed`.`Team_TeamID`=`Team`.`TeamID`;
END;
$$
See eg http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
I have a quotes table and a jobs table in a MySQL database. I want to automatically create a job number when I change the quote disposition to PO obtained. The disposition field in an enum so their will be no variance.
The JobNum field is auto-incremented so I felt inserting the bid number into the table would auto generate a new row and thus a job number.
This is the script I was playing with.
DELIMITER $$
CREATE
TRIGGER create_job AFTER UPDATE
ON Quotes
FOR EACH ROW BEGIN
IF Quotes.QuoteDispo = PO obtained
INSERT INTO Jobs (BidNum)
SELECT BidNum
FROM enjouede_delham.Quotes
END$$
DELIMITER ;
I would also like to create a pop-up warning prior to the action in case of entry error. Is this possible with PHP or must I use JavaScript? I am using PHPRunner to create the data entry forms but can insert custom scripts for functionality.
the first sql command is:
INSERT INTO table1(post) values('$post');
and after insert $post I want to update a column in another table
so I used:
UPDATE table2 SET score='$score' where name='$name';
how do I combine these 2 command or do them at the same time ?
I am new to mysql :)
here is what I want:
a user go to my website and post an string after post it the score of that user will be update
If for every insert you update, you could add triggers to your database.
Code :
delimiter |
CREATE or REPLACE TRIGGER TriggerName
AFTER INSERT
ON table1
BEGIN
UPDATE table2 SET score=score + 1 WHERE name=INSERTED.user_id
# INSERTED is the row added to table1
END;
delimiter ;
If you have the user id field in table1, this should work.
Otherwise, if you use a relation-table, like user_post (id, user_id, post_id), you have to declare a variable to store the id temporarily
If you don't like maintaining two applications from now on (the one you have and the one you create in the database by adding triggers or functions), there is a simpler solution:
Use only one piece of PHP code to add this stuff to the database (like a function or class' method), and simply send the two queries one after the other.
For extra data consistency, you should use a transaction, which is simply two more queries, or an appropriate usage of the database classes. For example, MySQLi has http://php.net/manual/en/mysqli.begin-transaction.php to start the transaction and http://php.net/manual/en/mysqli.commit.php to end it (or http://php.net/manual/en/mysqli.rollback.php to undo).
function writePostWithScore($post, $name, $score) {
// have the mysqli connection object somewhere
$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
$mysqli->query("INSERT INTO table1 (post) values('".$mysqli->real_escape_string($post)."')");
$mysqli->query("UPDATE table2 SET score='".$mysqli->real_escape_string($score)."' where name='".$mysqli->real_escape_string($name)."'");
$mysqli->commit();
}
I always create functions. Create 2 functions. One that insert, the otherone will update. Call what you need.
I have a mysql database with 12,000 entries, what i want setup is the ability to monitor a column in the database and if/when the column is altered for any entry it sends me an email with the details.
EDIT: I have access to mysql db, but not the script which works with it. So it should monitor it for changes...
You could create some triggers on the table, if your version of MySQL has them. A trigger can then invoke any function you care to create. A trigger has the advantage that any insertion or deletion or any update of the column will cause it to fire; you wouldn't have to change any other code to make it happen. See here for more... http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Create a trigger on update
Create another table (lets call it cron_table), where the trigger will insert information of the updated row (may be old value, new value etc)
Setup a cron, which will call a script which will check the cron_table and send email if any entry is found. Cron interval can be setup according to need.
--- If you could send email from trigger, there would be no need for a separate table and cron ---
try something similar to this , you can edit the function to send you and email if the query has insert and TABLE_NAME or COLUMN_NAME in it
set up one column to be a datetimestamp.
This will update on every change of the row. There you can run a sql query either via a cron job or after every few php queries to return you the list of changed rows since the last check.
Select * from tbl_myentries where EntryUpdated > '$TimeSinceLastCheck'
you need to understand Data Manipulation Language (DML) triggers
in my sql: use
CREATE TRIGGER salary_trigger
BEFORE UPDATE ON table_name
REFERENCING NEW ROW AS n, OLD ROW AS o
FOR EACH ROW
IF n.columnName <> o.columnname THEN
END IF;
;
Create a trigger on a change on your column, then insert it to another table as log table.
Run cron job on your table that will send you an email.
I have an application where I need to INSERT an auto_increment value from a PK in another table. I know how to do this in PHP, but I need to have this done at the DB level, since I cannot change the program logic.
I am new to triggers, so I'm sure this will be an easy answer for someone. Here is what I have so far:
DELIMITER //
CREATE TRIGGER new_project AFTER INSERT ON m_quality_header
FOR EACH ROW
BEGIN
INSERT INTO m_quality_detail (d_matl_qa_ID) VALUES (NEW.h_matl_qa_ID);
END//
DELIMITER ;
I just want the value of the auto_increment value from h_matl_qa_ID to be inserted as a new record into d_matl_qa_ID. The error I get is:
"This version of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table'
But, I don't want to update the table that has the trigger, so why is my current code considered a 'multiple' trigger?
This is on MySQL 5.0.45-7.el5 running on a CentOS 5 server (64-bit Intel) If I have to, I can modify the PHP code, but that needs to be the last resort.
If you've tried to create the trigger before, as outis states above you can issue the command
SHOW TRIGGERS;
and it will tell you.
If that is the case, what I typically do is issue
DROP TRIGGER IF EXISTS my_trigger_name;
and then recreate the trigger.
Your trigger code, otherwise, looks OK.
DELIMITER //
DROP TRIGGER IF EXISTS new_project//
CREATE TRIGGER new_project AFTER INSERT ON m_quality_header
FOR EACH ROW
BEGIN
INSERT INTO m_quality_detail
(d_matl_qa_ID, d_matl_qa_project_test_number) VALUES (LAST_INSERT_ID(), LAST_INSERT_ID());
END//
DELIMITER ;