1

So i have the following table:

Table: competence
Columns:
id  int(11) AI PK
name    varchar(400)
organization_id int(11)
competence_type_id  int(11)
competence_category_id  int(11)

And the following user table:

    Table: user
Columns:
id  int(11) AI PK
username    varchar(100)
password    varchar(100)
is_active   int(11)
user_type_id    int(11)
token   varchar(445)
organization_id int(11)
title_id    int(11)
image_path  varchar(100)
division_id int(11)

And the following connection between these two tables:

Table: user_has_competence
Columns:
user_id int(11) PK
competence_id   int(11) PK
competence_level_id int(11)
progression varchar(45)
id  int(11) AI PK

Now im trying to create a trigger on the competence table that does the following:

After a row has been inserted into the competence table find all users with the same organization_id and then for each of these users insert into user_has_competence with the user_id and competence_id.

However i havnt worked with triggers that much and was hoping one of you guys could push me in the right direction.

0

1 Answer 1

7

In mysql it could be done as

delimiter //
create trigger competence_ins after insert on competence
for each row 
begin
 insert into user_has_competence (user_id,competence_id)
 select u.id,c.id from competence c
 join user u on u.organization_id = c.organization_id and c.organization_id = new.organization_id;
end;//

delimiter;
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much mate! :D +1 do you know how i would do whenever i create a user it should add all competences from the competence table where the organization_id is the same?
Yes it would be pretty much same. if you provide an example I can write a query for that.
Actually when you add an user you also add organization_id and in competence table you have organization_id. So if you insert into user_has_competence it may happen that for same organization id there multiple data so do you want each of them and newly added user_id into the user_has_competence ?
what i need is basicly: When a new user is added to the database it automaticly adds all competences to competence_has_user and when a new competence has been added then all users in the organization has to get the competence
Well that perhaps going to have some logical issue, since when you add any user you do not know anything about competence, all you can get those data from competence having same organization id into the user_has_competence now say you add a new competence and using same trigger you may have duplicate entry. So I would suggest to make it one way. I would suggest to create a new question.

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.