1

I have three MYSQL tables that all relate to each other as you can see below.

I'm currently storing the dateofjob twice because i do not know how to create table joins in a trigger. Currently i'm using this trigger on the specimen details table

CREATE TRIGGER `NewAge_update` BEFORE UPDATE ON `Speciemn_Details`
 FOR EACH ROW BEGIN
    SET NEW.Due_Date = DATE_ADD(NEW.CastDate,INTERVAL NEW.Age DAY);
END

And this is working perfectly, but i want to be able to remove the column dateofjob from the specimen details table and calculate the duedate from the Job_Details table to save myself from having double data.

I will have to join the job_details.ID with the Test_Details.PARENTID and the Test_Details.TESTID with the specimen_details.TESTID, I just don't know how to do this inside a trigger. any help would be appreciated greatly

I've attempted to be as detailed as possible BUT If anymore information is required please ask me

Job_Details

 +----+-----------+
 | ID | dateofjob |
 +----+-----------+
 |  1 | 1/01/2015 |
 |  2 | 1/01/2016 |
 |  3 | 1/01/2017 |
 +----+-----------+

Test_Details

+----------+--------+--------------+
| ParentID | TestID | TestLocation |
+----------+--------+--------------+
|        2 |   2154 | Barn         |
|        2 |   2155 | Barn         |
|        1 |   8055 | Yard         |
+----------+--------+--------------+

Specimen_Details

+--------+----------+---------+-----------+-----------+
| TestID | Specimen | TestAge | dateofjob |  Duedate  |
+--------+----------+---------+-----------+-----------+
|   2154 | A        |       3 | 1/01/2016 | 4/01/2016 |
|   2154 | B        |       8 | 1/01/2016 | 9/01/2016 |
|   8055 | A        |       2 | 1/01/2015 | 3/01/2015 |
+--------+----------+---------+-----------+-----------+

1 Answer 1

0

Joins inside trigger code really aren't any different from joins in any other procedural code, except that you can't query the triggering table and you instead have the OLD and NEW pseudorecords. If I've understood your description, you want to do something like

CREATE TRIGGER `NewAge_update` BEFORE UPDATE ON `Specimen_Details`
  FOR EACH ROW
  BEGIN
    DECLARE jobdate DATE;
    SELECT dateofjob
      INTO jobdate
      FROM job_details j, test_details t
      WHERE j.ID = t.ParentID
        AND t.TestID = NEW.TestID;
    SET NEW.Duedate = DATE_ADD(jobdate, INTERVAL NEW.TestAge DAY);
  END;

(Don't forget that trigger bodies are procedural, so you don't have to do everything in a single statement.)

1
  • Thank you so much, I've been scratching my head over this for a few days. Worked Perfectly!
    – Luke Smith
    Jan 30, 2016 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.