I have 2 tables
1. Parent
Parent_ID(PK)| name | status
--------------------------------
1 |parent 1 |enable
2 |parent 2 |enable
3 |parent 3 |disable
2. Child
Child_Id(PK)| Parent_ID(Fk of parent table) | name | status
----------------------------------------------------------
1 |1 | child 1 | enable
2 |1 | child 2 | enable
3 |1 | child 3 | enable
4 |1 | child 4 | enable
5 |2 | child 5 | enable
6 |2 | child 6 | enable
7 |2 | child 7 | enable
8 |2 | child 8 | enable
9 |3 | child 9 | disable
10 |3 | child 10 | disable
11 |3 | child 11 | disable
12 |3 | child 12 | disable
Now I want to set a relation between both the tables such that if status of a record in parent tables changes then status of all its child row should also get changes.
I know I can do this with triggers but I think there should eb some way to do this with relations and FK constraint on multiple columns.
You need to create a composite foreign key in the
child
table referring toparent_id
andstatus
.Here's a demo:
Test:
Now try to update the
status
field ofID = 1
in parent table.This change will trigger the change in the status values of all the child entries in the
child
table too.Output:
Same holds for
DELETE
operationSee Demo
And if you need to add foreign key constraint later: