I need to update a table with pre-calculated values from tables where data can be added/updated/deleted.
I could use
insert into precalculated(...)
select ... from ...
on duplicate key update ...
to add/update the pre-calculated table but is there an optimized method to delete the obsolete rows ?
I think you should create a stored procedure that deletes the data of your related tables if and only if the records fulfill a condition.
There's not enough information in your question to design the procedure, but I can give you a little example:
delimiter $$
create procedure delete_orphans()
begin
declare id_orphan int;
declare done int default false;
declare cur_orphans cursor for
select distinct d.id
from data as d
left join precalculated as p on d.id = p.id
where p.id is null;
declare continue handler for not found set done = true;
open cur_orphans;
loop_delete_orphans: loop
fetch cur_orphans into id_orphan;
if done then
leave cur_orphans;
end if;
delete from data where id = id_orphan;
end loop;
close cur_orphans;
end$$
delimiter ;
This procedure will delete every row in the data table that does not have at least one related row in the precalculated table.
Of course, this approach might be inneficient, because it will delete the rows one by one, but as I said this is only an example. You can customize it to fit your needs.
You can call this procedure from a trigger if you want (with call delete_orphans()).
Hope this helps.
Since you are always adding or updating rows that exist in these other tables, and you want to remove any rows that don't exist, why don't you just :
DELETE FROM precalculated
insert into precalculated(...)
select ... from ...
on duplicate key update ...
Always starting clean means you don't have to worry about orphans later.
You could add triggers for insert, delete and update on the main tables that maintains precalculated.
When inserting or updating the same code can be used to calculate the values and issuing a replace into precalculated (...) values (...)
When deleting it's probably the same, with the addition that you'll also delete rows from precalculated that are orphans. Be smart here and use values from the original delete to query precalculated for orphans instead of doing a table scan.
I may have found my solution using rename.
so basically, I will do a simple insert select to the temporary table and then
rename precalculated to precalculated_temprename, precalculated_temp to precalculated, precalculated_temprename to precalculated_temp;
truncate precalculated_temp;
need some tests but it seems the rename operation is fast and atomic.
Related
I'm having a little issue with a trigger in a MySQL database. I have a DB with two tables: "tasks" and "files". The "tasks" table have a field which is a foreign key of the primary key from the "files" table. It also sometimes may be null.
What I'm trying to acomplish is to delete in the first place a row in the "tasks" table, and after that delete the corresponding row in the "files" table using a trigger.
This is the trigger I'm using right now:
DELIMITER //
CREATE TRIGGER after_delete_file AFTER DELETE ON tasks
FOR EACH ROW
BEGIN
DECLARE fileId int;
SELECT file INTO fileId FROM tasks WHERE id=old.id;
DELETE FROM files WHERE id=fileId;
END;//
DELIMITER ;
The field "file" in the "tasks" table is the one containing the foreign key. In the examples I've been running, that field has never been null.
The problem is that the select statement always returns null. The delete statement that triggers this trigger goes fine, but the row in the "files" table is never deleted. I've tried to insert the "fieldId" variable on a testing table, and it's always saving a null value.
Is there any problem on that trigger? Maybe I'm trying to do something merely impossible?
All the help is much appreciated :)
Since it should be looping over each deleted row, why would this not work?
DELIMITER //
CREATE TRIGGER after_delete_file AFTER DELETE ON tasks
FOR EACH ROW
BEGIN
DELETE FROM files WHERE id=old.file;
END;//
DELIMITER ;
If that doesn't work, could try this:
DELIMITER //
CREATE TRIGGER after_delete_file AFTER DELETE ON tasks
FOR EACH ROW
BEGIN
DELETE FROM files INNER JOIN tasks ON files.id=tasks.file WHERE tasks.id=old.id;
END;//
DELIMITER ;
but I don't think that should be necessary.
AFTER delete means that the data is deleted, of course you can't find it. Try creating the trigger for BEFORE delete.
You could also more carefully use all of the old values rather than selecting from the table that was deleted from.
I was trying to create trigger which can update value of column user_count of table user_details using value of u_count of table user_info.
CREATE TRIGGER `test`
AFTER INSERT ON `user_details` FOR EACH ROW
BEGIN
DECLARE default_user_count int(11);
SELECT u_count INTO #default_user_count FROM
user_info WHERE user_info.id= user_details.id_c;
IF user_details.user_count= 0
THEN UPDATE user_details SET
user_count = default_user_count
WHERE user_details.id_c = user_info.id;
END IF;
END
Trigger saved successfully but when i tried to insert value in both table it is preventing to insert record into user_details means no row inserted in 2 this table, if we delete trigger then its working.
Can anyone let me know wrong with this trigger?
THanks,
M.
It's not really clear what you're trying to accomplish, but it seems like it's something like what we have below.
There are numerous errors in and ambiguities in your trigger.
Confusion on variables -- DECLARE default_user_count INT(11); does not declare the user-defined variable #default_user_count. It declares the program variable default_user_count. The # prefix references an entirely different variable scope and namespace.
SELECT and UPDATE from the table which invoked the trigger doesn't usually make sense (SELECT) or is completely invalid (UPDATE).
With in a trigger, you are operating FOR EACH ROW -- that is, for each row included in the statement that invoked the trigger. Inside an INSERT trigger, the NEW values for the row are in a pseudo-table/pseudo-row accessible via the alias NEW. For UPDATE triggers, there are NEW and OLD row values, and for DELETE triggers, just OLD.
AFTER INSERT doesn't seem to make sense. I think you're looking for BEFORE INSERT -- that is, while processing an INSERT INTO ... query, before the newly-inserted row actually gets written into the table, modify its values accordingly. The resulting row contains the original values except where the trigger has modified them.
SELECT ... INTO a variable is a practice you should not get into the habit of, because it can bite you in a way a scalar subquery can't, by leaving a variable unexpectedly unaltered instead of setting it to NULL as would be expected. In this case, it would have made no difference, but it's still a caution worth mentioning... and in this case, I've eliminated that intermediate variable altogether, so the subquery is the only option.
If you are trying to set a value in this table using a value found in another table, all you need to do is SET NEW.column_name equal to the value you want used in the row instead of the value provided with the insert statement.
CREATE TRIGGER `test`
BEFORE INSERT ON `user_details` FOR EACH ROW
BEGIN
IF NEW.user_count = 0 /* maybe also >> */ OR NEW.user_count IS NULL /* << this */ THEN
SET NEW.user_count = (SELECT ui.u_count
FROM user_info ui
WHERE ui.id = NEW.id_c);
END IF;
END
Again, it's unclear how the two tables are connected based on the content of the original question, but this appears to do what you're trying to accomplish.
To futher clarify i was trying to create a trigger that checks a table for a number in sql.
If it finds said number then it erases that entire row.
It uses a separate table of names to check.
I thought it be could done using a join but have had no luck.
So it would look like this I suppose if(tb1.name = tb2.name) then DELETE row.
I'm sorry if the formatting is off.
EDIT; I am using phpmyadmin so some of the the code may be missing but here is the code from my latest "attempt"
It uses on INSERT and time is set to AFTER
SELECT * FROM flights WHERE NOT EXISTS (SELECT * FROM no fly list WHERE PassengerId.Id = Passenger.Id)
have not added the DELETE as of now but the work is somewhat ongoing
Assuming that flight and dnf both have passenger_id column that uniquely identifies a passenger of interest then your trigger might look like this
DELIMITER $$
CREATE TRIGGER dnf_insert AFTER INSERT
ON dnf
FOR EACH ROW BEGIN
DELETE FROM flights WHERE passenger_id = NEW.passenger_id;
END$$
DELIMITER ;
If you post DDL (create table statements) for all relevant tables we can refine the query
I am wondering if it is possible to perform a SQL query then update another table with the generated ID and continue through all of the rows?
I have this SQL query that works but what I need to do is after each row is added to cards to then update merged.cars_id with the last generated ID so they are linked. normally I would do this with PHP but ideally I would like to just do it with MySQL if possible.
MAIN QUERY
INSERT INTO cards (first_contact_date, card_type, property_id, user_id)
SELECT first_contact_date, 'P', property_id, user_id FROM merged
THEN I NEED WITH MATCHING ROWS (Roughly)
UPDATE merged SET merged.card_id = LAST_INSERT_ID (FROM ABOVE) into the matching record..
Is something like this possible and how do I do it?
I would recommend using MySQL triggers to do this
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
A trigger is a function that will be executed AFTER or BEFORE the INSERT or DELETE or UPDATE is done over any record of your table.
In your case you need to do a AFTER INSERT on cards that just updates the merged table. Make sure its AFTER insert as you wont be able to access the new row's ID otherwise.
The code would look something like this, assuming the id field from the cards table its named "id"
delimiter |
CREATE TRIGGER updating_merged AFTER INSERT ON cards
FOR EACH ROW BEGIN
UPDATE merged SET card_id = NEW.id;
END;
|
delimiter ;
May I suggest Stored Procedures?
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
--EDIT--
Ah yes, triggers. For this particular situation, Jimmy has the answer. I will leave this post for the sake of the link.
I would set up a trigger to do this. For mysql, read http://dev.mysql.com/doc/refman/5.0/en/triggers.html. This is what triggers are designed to handle.
Hello, every one :)!
I'll try and keep this as simple as possible, basically, I have one table that references itself via a parent_id column. Each row in the table can have a parent and can keep count of how many children it has via the count column. So essentially what I'm trying to do is have the triggers update each parent row's count column when necessary
The problem is that the update trigger gets called when the update operation in the insert trigger gets called. Then I get:
"General error: 1442 Can't update table 'term_taxonomies' in stored function/trigger because it is already used by statement which invoked this stored function/trigger".
Any ideas?
Actual code:
TRIGGER `dbname`.`ai_term_taxonomies`
AFTER INSERT ON `dbname`.`term_taxonomies`
FOR EACH ROW
BEGIN
IF NEW.parent_id NOT 0 THEN
UPDATE term_taxonomies as termTax SET assocItemCount = (assocItemCount + 1)
WHERE termTax.term_taxonomy_id = NEW.parent_id;
END IF;
END$$
CREATE
TRIGGER `dbname`.`au_term_taxonomies`
AFTER UPDATE ON `dbname`.`term_taxonomies`
FOR EACH ROW
BEGIN
IF NEW.parent_id NOT OLD.parent_id THEN
IF NEW.parent_id NOT 0 THEN
UPDATE term_taxonomies as termTax SET assocItemCount = (assocItemCount + 1)
WHERE termTax.term_taxonomy_id = NEW.parent_id;
END IF;
IF OLD.parent_id NOT 0 THEN
UPDATE term_taxonomies as termTax SET assocItemCount = (assocItemCount - 1)
WHERE termTax.term_taxonomy_id = OLD.parent_id;
END IF;
END IF;
END$$
All mysql triggers execute in the same transaction as the triggering statement.
You want to update using the SET NEW.assocItemCount syntax as opposed to performing an UPDATE statement on the underlying table.
Edit: However, in your case this is not possible because you are updating a different row in the same table, the hardest thing to do in a mysql trigger. Sorry.
You will have to change your schema. Take assocItemCount out of your table, create a new table holding just term_taxonomy_id and assocItemCount, and update that using an UPDATE statement from your query. It is also possible to use a view joining these two tables to hide this detail if a query needs to use your original schema.
Alternatively, if you did not have assocItemCount in your database at all, you would still be able to compute it in any queries, and your database would be better normalized than it is now.