Question

What is the best way to proceed in the following scenario

I have my first_table which holds Datas and a second one which is related to this on ID (ID = id=related) and there are no foreign keys involved

first_table
----------------------------------------------
ID   | Datum      | Type          |Status
----------------------------------------------
123  | 2013-09-11 |   relational  |   1
----------------------------------------------
1234 | 2013-09-11 |   relational  |   1
----------------------------------------------
185  | 2013-09-11 |   normal      |   1
----------------------------------------------

In my second_table there is an status update on interaction which means I set 0 as value.

And here comes the thing where I have problems to step forward, because I try to solve this issue on mysql side not involving server side scripts

If SELECT * FROM second_table WHERE id_related = '1234' AND status = 1 is empty I want to update my first tables status setting it's value 0

UPDATE first_table SET status = 0 WHERE ID = 1234

second_table
---------------------------------------------
ID | id_related   | some_column_value | status
---------------------------------------------
1  | 123          | some_column_value | 1
---------------------------------------------
2  | 123          | some_column_value | 0
---------------------------------------------
3  | 1234         | some_column_value | 0
---------------------------------------------
4  | 1234         | some_column_value | 0
---------------------------------------------

Is there a way to do all this with MySQL setting up a trigger?

Was it helpful?

Solution

If you need to keep the status values up-to-date during INSERTs you can create trigger:

CREATE TRIGGER `tr1` AFTER INSERT ON `second_table`
  FOR EACH ROW
BEGIN
    IF NOT EXISTS (SELECT * FROM second_table WHERE status = 1 AND id_related = NEW.id_related ) THEN
        UPDATE first_table SET status = 0 WHERE ID = NEW.id_related;
    ELSE
        UPDATE first_table SET status = 1 WHERE ID = NEW.id_related;
    END IF;
END;

This will keep 1 for status in first_table while there are related rows in second_table having 1 as status and 0 otherwise. If you need to perform the same operation for UPDATEs of the second_table, you need to create the 'AFTER UPDATE' trigger with the same body as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top