How can I distinguish between possible foreign key values?

I have three tables in a MySQL database. This is the main table associated with the organization. Each organization has a unique identifier, which is also a foreign key in some tables.

org
+------------+-------------+ 
| org_id     | name        |   
+------------+-------------+ 
| 1          | a           | 
| 2          | b           |  
| 3          | c           |  
+------------+-------------+

This is a group table. Organizations can have many groups.

groups
FOREIGN KEY (ORG_ID) REFERENCES ORG (ID);
+------------+-------------+----------+ 
| ID         | org_id      |   name   |
+------------+-------------+ ---------+
| 1          | 1           |  Group1  |
| 2          | 2           |  Group2  |
| 3          | 2           |  Group3  |
+------------+-------------+----------+

And this is the feed table in which I would like to update. A channel can contain only one linked group.

feed
FOREIGN KEY (GROUP_ID) REFERENCES GROUPS (ID);
+------------+-------------+--------------+ 
| ID         | org_id      |   group_id   |
+------------+-------------+ -------------+
| 1          | 1           |      1       |
| 2          | 2           |      2       |
| 3          | 1           |     NULL     |
| 4          | 2           |      3       |
+------------+-------------+--------------+

, , . INSERT UPDATE , groups_id, groups_id, . , GROUPS FK. , . INSERT UPDATE groups_id, org_id, feeds.org_id.

, . INSERT INTO feed VALUES (4, 2, 1), . , , ...

. , , . , , .

, , ?

EDIT:

, . /. , . . .

, :

UPDATE feed 
SET title = "Title", message = "Message", groups_id = "1" 
WHERE id = "1" AND org_id = "1"

:

UPDATE feed 
SET title = "Title", message = "Message", groups_id = "2" 
WHERE id = "1" AND org_id = "1"

, ( org 1), org ( 2 org 2).

, , FOREIGN KEY (, , ). db?

+4
1

, :

create table agroup (
  id int primary key,
  orgid int,
  UNIQUE (id,orgid)
);

create table feed (
  id int primary key,
  groupid int,
  orgid int,
  FOREIGN KEY (groupid, orgid) REFERENCES agroup(id, orgid)
);

insert into agroup values (10, 1), (20, 1), (30, 2), (40, NULL);
insert into feed values (100,10,1), (101, 20, 1);
insert into feed values (102, 40, NULL); # works
insert into feed values (103, NULL, 1); # works as well
# insert into feed values (110,10,2); # yields error "Cannot add or update a child row: a foreign key constraint fails"

UNIQUE(id,orgid), . , agroup(id primary key) , agroup(id,orgid) , unique(id,orgid). , . , .

EDIT: , NULL- .

MySQL, NULL () , , NULL . NULL- , . Confer mysql , : "... MySQL , MATCH SIMPLE, NULL. ( ), , () . ."

+3

Source: https://habr.com/ru/post/1664223/


All Articles