this question is applicable on different RDBMS: MySQL and SQL Server
I’ve been searching for this all night and I can’t find it on the net. My problem is all about uniqueness and foreign keys. Consider the following schema:
CREATE TABLE Male
(
StudentID INT,
FirstName VARCHAR(20) NOT NULL,
MiddleName VARCHAR(20) NOT NULL,
LastName VARCHAR(20) NOT NULL,
-- other columns ...
CONSTRAINT male_PK PRIMARY KEY (StudentID),
CONSTRAINT male_UQ UNIQUE (FirstName, MiddleName, LastName)
);
CREATE TABLE Female
(
StudentID INT,
FirstName VARCHAR(20) NOT NULL,
MiddleName VARCHAR(20) NOT NULL,
LastName VARCHAR(20) NOT NULL,
-- other columns ...
CONSTRAINT Female_PK PRIMARY KEY (StudentID),
CONSTRAINT Female_UQ UNIQUE (FirstName, MiddleName, LastName)
);
CREATE TABLE ClassList
(
ClassID INT,
Name VARCHAR(30),
ClassYear INT,
-- other columns ...
CONSTRAINT ClassList_PK PRIMARY KEY (ClassID),
CONSTRAINT ClassList_UQ UNIQUE (Name, ClassYear)
);
The reason why table Male and Female are separated is because they are maintained by different sql accounts.
The problem now is the Association Class.
CREATE Student_Class
(
SudentID INT,
ClassID INT,
CONSTRAINT tb_UQ UNIQUE (StudentID, ClassID)
)
So my questions are:
- How can I set the uniqueness of the
StudentIDfrom both tablesMaleandFemale. I can’t find that on the net. - How can I enforce
Foreign Keyconstraints in which the value column of the association class table come from two tables:MaleandFemale?
Suggestions are also Accepted.
Thank You
I don’t think it’s a great idea to let user privileges dictate your schema but if you have to then I think the idea mentioned by HerpaMoTeH is a good one. A third table with id, gender and with the id used as an FK in the gender specific tables and student_class.
Another solution is to just split your student_class table into two:
male_student_class and female_student_class
Alternatively you could create 2 sets of stored procedures (male and female) for CRUD operations on a single student table. Then you would deny priviliges to the actual table for your users but grant them access to the appropriate set of stored procedures. Your schema would be simplified to: