Limit the number of related records at the database level

Suppose I have two tables parentsand children. Naturally, parents can have many children with a one-to-many association. Is there any construction in MySQL or PostgreSQL that would allow limiting the number of related objects, for example:

FOREIGN KEY (parent_id) 
  REFERENCES parent(id)
  LIMIT 3

Does it have something like this, or do we need to have a custom trigger?

+4
source share
1 answer

. , ( PostgreSQL, SQL):

CREATE TABLE child (
   child_id  serial PRIMARY KEY
 , parent_id int NOT NULL REFERENCES parent
 , child_nr  int NOT NULL
 , CHECK (child_nr BETWEEN 1 AND 3)
 , UNIQUE (parent_id, child_nr)
);

, 1 3 - . .

(parent_id, child_nr), PK child_id. ...

, , , , . concurrency, , , , .

child_nr?

(), . child_nr . .

( , ). (parent_id, child_nr) NULL.

UPDATE, INSERT DELETE (GRANT/REVOKE), , . FK parent ON DELETE CASCADE, .

Alternative

, : parent <= 3. child . .

+2

All Articles