0

I have 2 tables setup in my database - fitness_report and result.

fitness_report has the following columns (in order):

report_id, test_period, test_date, student_id

results has the following columns (in order):

test_id, student_id, report_id, score

What I need to happen is when a new row is created on table fitness_report, entries are made to the results table as follows, where student_id and report_id are copied from the new row made on fitness_report:

1, student_id, report_id, null
2, student_id, report_id, null
3, student_id, report_id, null
4, student_id, report_id, null
5, student_id, report_id, null
6, student_id, report_id, null

Could you please suggest the best way to go about doing this.

Cheers

0

1 Answer 1

1

You can create a trigger on INSERT event. Check this.

CREATE TRIGGER myTrigger AFTER INSERT ON fitness_report 
  FOR EACH ROW BEGIN
    INSERT INTO results SET student_id = NEW.student_id, report_id=NEW.report_id;  
  END;
Sign up to request clarification or add additional context in comments.

5 Comments

That'll insert the student_id and report_id into the results table, but how do i insert the static data as well? (test_id and score)?
Would this work: CREATE TRIGGER newReport AFTER INSERT ON fitness_report FOR EACH ROW BEGIN INSERT INTO results(1, NEW.student_id, NEW.report_id, null); INSERT INTO results(2, NEW.student_id, NEW.report_id, null); INSERT INTO results(3, NEW.student_id, NEW.report_id, null); INSERT INTO results(4, NEW.student_id, NEW.report_id, null); INSERT INTO results(5, NEW.student_id, NEW.report_id, null); END;
Try INSERT INTO results SET student_id = NEW.student_id, report_id=NEW.report_id, score=null;. You can repeat the INSERT statement to insert multiple records.
I'm getting the following error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
Let me know if it works. I'll update the answer acordingly. Although AFTER INSERT is preferred. You can check for syntax in documentation.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.