3 , ?
, , .
SQL- SQL-92:
CREATE TABLE Students
(
student_name VARCHAR(20) NOT NULL UNIQUE
);
CREATE TABLE StudentPhonebook
(
student_name VARCHAR(20) NOT NULL
REFERENCES Students (student_name),
phone_number CHAR(8) NOT NULL
CHECK (phone_number LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'),
UNIQUE (student_name, phone_number)
);
CREATE ASSERTION students_max_three_phone_numbers
CHECK (
NOT EXISTS (
SELECT *
FROM (
SELECT student_name, COUNT(*) AS tally
FROM StudentPhonebook
GROUP
BY student_name
) AS DT1
WHERE tally > 3
)
);
MySQL does not support CHECKany taste, and the SQL product does not support CREATE ASSERTION, so the above restrictions must be written using procedural code, for example. triggers.
Of interest, if your SQL product supports row CHECK-level constraints at the row level (as is usually done), you can use an attribute occurrencewith a constraint BETWEEN 1 AND 3, and then include this attribute in a key constraint, for example.
CREATE TABLE StudentPhonebook
(
student_name VARCHAR(20) NOT NULL
REFERENCES Students (student_name),
phone_number CHAR(8) NOT NULL
CHECK (phone_number LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'),
occurrence INTEGER DEFAULT 1 NOT NULL
CHECK (occurrence BETWEEN 1 AND 3),
UNIQUE (student_name, phone_number),
UNIQUE (student_name, occurrence)
);
source
share