Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL: set trigger to get the sum of rows

This is the results table:

student_id | subject_id  | get_ca1  | get_ca2  | get_exam | get_total
----------------------------------------------------------------------
   101     |     1       | 10       | 7        | 10       |
   102     |     2       | 5        | 5        | 10       |
   103     |     1       | 9        | 10       | 4        |
   101     |     1       | 8        | 10       | 10       |
   103     |     2       | 2        | 10       | 10       |
   104     |     1       | 7        | 8        | 5        |
   101     |     2       | 7        | 8        | 5        |

I want to create a trigger that will sum up the rows get_ca1 + get_ca2 ...+ get_exam and store the total in the get_total column.
When the rows get_ca1, get_ca2,... get_exam are inserted, the trigger should calculate the total and store in the get_total column.

I just learnt about triggers today so I’m not knowledgeable in it at all. But so far, this is what I tried and it of course threw an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CREATE TRIGGER `sum total ` AFTER INSERT ON `exam_group_exam_results`
FOR EACH ROW SET get_tot_score = (get_ca1 + get_ca2 + get_ca3 + get_ca4 + get_ca5 + get_ca6 + get_exam);

>Solution :

Mysql doesn’t know where your columns belog because you are missing a reference to the NEW row.

Also you can only change values, before the row was inserted

so use

CREATE TRIGGER `sum_total_before_INSERT` BEFORE INSERT ON `exam_group_exam_results`
FOR EACH ROW 
SET NEW.get_tot_score = (NEW.get_ca1 + NEW.get_ca2 + NEW.get_ca3 + NEW.get_ca4 + NEW.get_ca5 + NEW.get_ca6 + NEW.get_exam);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading