Foreign key for different entities - database

Say if a real life operation like loaning a library book is to be performed on two entities Teacher and Student. And the operation details are present in a table like Loans or Transaction. How do I define a foreign key in the Loans table for both Teacher and Student which have different schemes for primary keys? (student has 6digit key but teacher has 4 digit)
A similar question arises when a hospital database system Appointment table attempts to link to both an Employee table and EmployeeRelatives table using a foreign key, where both Employees of the hospital and their relatives are to be given free treatment. How does one specify format of foreign key in Appointments table?

A foreign key can reference only one table.
My solution in these cases is to introduce an additional table (People or whatever name you prefer) which contains all the IDs of Teacher and Student. Teacher and Student can also have the People table key as foreign key.
You can find other possible solutions here:
Foreign Key to multiple tables

Related

Many to Many association table PK as FK in other table

I have the following tables: school, teacher, school_teacher and student.
school_teacher is a many-to-many junction table using an autogenerated PK and the FKs of school and teacher.
A student belongs to a teacher of a particular school and a teacher of a school has many students.
My question is whether I should create the foreign key in the student table to point to school_teacher table PK or to the two tables PKs (school, teacher) individually?
I believe it would be best for referential integrity to reference school_teacher to ensure that transaction records are only inserted if there is a relationship between the school and the teacher. In terms of best practices, what is the best option or the best way to address this problem? Is there any other possibility better than the ones I mention?
In general, is there a problem in which the primary key of an association table is a foreign key in another table?
This is simply an example. In a real case a student could have more than one teacher. It is to simplify the example.
Student * ------ 1 School *------*Teacher
Will you check for student belongs to a school or many schools?

Which table should be Parent table and which should be child table?

Hi have two tables Auther and Books.
I am confused that to which table should i keep as parent table and which should be child table for making foreign key constraint.
CREATE TABLE author
(
author_id NUMBER(3) CONSTRAINT athr_aid_pk PRIMARY KEY,
author_name VARCHAR2(30)
);
CREATE TABLE books
(
book_id NUMBER(3),
book_title VARCHAR2(30),
book_price NUMBER(3),
);
Please explain me which table should be Parent table and why?
Answer: None.
Reason: This is a many-to-many relationship. An author can have any number of books written, also a book can have more than one author.
Solution: Make a separate table with two columns author_id, book_id both are foreign keys.
You have been given the correct answer already. I'd like to add the technical view: columns to add.
A foreign key constraint means you have a column or a set of columns in a table that uniquely identify a record in another table.
In order to have a foreign key on a book in table author you'd add book_id to that table. But that wouldn't make sense. Which of the author's books would you reference in this field? So books simply cannot be the parent table for the relation.
Then you can have it vice versa: Have author_id in table books, which would mean a book can only be written by one author. Does this suffice for what your database is to contain? Then this is the way to go.
These mentioned relations are 1:n relations (one author can write several books or one book can be written by several authors). But as mentioned, it is more typical for an author/book realation to be n:m (one author can write several books and one book can be written by several authors).
To introduce an n:m relation in a database you add a bridge table containing the IDs of both tables. And this bridge table would reference both parent tables with foreign keys.
You can make Author as your parent table and Books as child table.
Reason: An author can write multiple books but a book(usually) is written by one author only.
I'd go for another approach than having a parent and a child table.
Create an extra table like this:
CREATE TABLE authors_books
(
author_id NUMBER(3),
book_id NUMBER(3),
PRIMARY KEY (`author_id`, `book_id`),
CONSTRAINT `FK_author_books__author`
FOREIGN KEY (`author_id`)
REFERENCES `author` (`author_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `FK_author_books__book`
FOREIGN KEY (`book_id`)
REFERENCES `books` (`book_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
);
This way you'll avoid any trouble with your n to m relationship between authors and books. Now one book can be written by multiple authors as well.
You probably wanna have an extra field orderas well to always maintain a unique PK. So the PK would be PRIMARY KEY (author_id,book_id,order).
Explanation 1
If you think about one to many relation from author to book then author will be parent. Actually author will be the owner of the relationship. He will map the realtion from author to books table.
Explanation 2:
If you think about many to many relation from author to book then none of will be parent. Both of them will have equal importance.
A FOREIGN KEY declaration says that each subrow of values that appears under listed columns of the table that REFERENCES also appears under the listed columns of the referenced table. The referenced columns have to be UNIQUE NOT NULL or a PRIMARY KEY. The "parent" table is the referenced one.
Whenever that's the case, declare a FOREIGN KEY. Otherwise don't.
It happens that if you JOIN on the two column lists, the result will have exactly one row per referencing table row.
With your two tables there's no foreign key to declare.
If you add a table author_books holding rows where "author AUTHOR_ID authored book BOOK_ID" then its author_id values have to be in author and its book_id values have to be in books. So declare two FOREIGN KEYs:
FOREIGN KEY (author_id) REFERENCES author (author_id)
FOREIGN KEY (book_id) REFERENCES books (book_id)
(If an author always wrote exactly one book then you could add book_id to author with a foreign key to books. If a book always had exactly one author then you could add author_id to books with a foreign key from author. But that's not the real situation with authors and books.)
Constraint declarations allow the DBMS to disallow erroneous changes that would make the database have a value that cannot be right. You don't need constraints to query a database. (Including UNIQUE NOT NULL, PRIMARY KEY or FOREIGN KEY.)

Foreign key for multiple columns of one table referenced to the same primary key?

I am currently creating a database using SQL but I have found the need to use a foreign key to in 3 different fields in a single table.
I have CourseID1, CourseID2 and CourseID3 in students courses table. Each of those 3 fields need to be foreign and reference to the CourseID field in the course table which is a primary key.
Is this possible? how do I go about doing this?
Thank you
This is possible. You would do:
foreign key (CourseId1) references Courses(CourseId),
foreign key (CourseId2) references Courses(CourseId),
foreign key (CourseId3) references Courses(CourseId),
That said, you don't want to do this. Having multiple columns with numeric appendages usually means that you want an association/junction table. In this case, you want a table named something like StudentCourses which would have one row per student and per course that the student takes.

DataBase Analysis-junction table

This matter confuses me,
I have a College Information system the junction table between students table and subjects(curriculum) table, the primary key is composite key (StudentID, SubjectID) and both of them are Foreign keys but the student may be fail in exam and repeat the subject so we will have duplicate PK and we need to record all data. I have two ways to solve this matter but i don't know the best way?
Add new column as primary Key instead of composite key.
Join to the composite key Season Column and year column and the composite key will be(StudentID, SubjectID, Season, Year). I have to mention that i don't need this composite key as foreign key.
Which way is better for performance and DB integrity?
Subject and exam are separate (if related) concepts, so you should not try to represent them within the same table. Also, the fact that an exam has been held for the given subject is separate from the fact that any particular student took that exam. Split all these concepts into their own tables, and the model becomes more natural, for example:
Representing a student that took the same exam several times is just a matter of adding multiple rows to the STUDENT_EXAM table.
NOTE: STUDENT_SUBJECT just records the fact that the student has enrolled in the subject, but not when (which year/semester). Keeping semester-specific information may require additional tables and more complicated relationships within the model.
NOTE: There is a diamond-shaped dependency in this model. Since SUBJECT_ID was passed from the "top" (SUBJECT), down both "sides" (STUDENT_SUBJECT, EXAM) and then merged at the "bottom" (STUDENT_EXAM) of the diamond, a student cannot take an exam on a subject (s)he has not enrolled in.

Database Design for student tracking system

EDIT: my revised Entity relationship diagram
A Student can have many contact times but this does not relate to what course they are on. So the courseID in tblContact was unnecessary, so I used to Primary keys in tblStudent relating to the grade for a particular tutor marked assignment and the course a particular student is on with that TMA.
Phew
http://i.imgur.com/cf3td.png
/Edit
My Old ERD
note that StudID and CourseID are a merged compound primary key
My question: Should I have studID and courseID in tblContact? or should I just have StudID, because I'm using a compound primary key I thought I should have both values in tblContact and tblStudentTMA?
Is this right?
The answer depends on whether the contact is related to a course or not.
If it relates to a course then you need some way of identifying the Course from the contact, but you can link to the tblCourse table from tblContact.
My preference for a many-many table is to use a separate primary key in your example StudentCourseID, which is a Identity column, this removes the need to store multiple foreign keys in a related table.
The primary key in tblContact has to have at least two columns. One of them has to be StudID.
It has to have at least two columns, because you need to store more than one contact per student. One of the columns has to be StudID to guarantee the contact row refers to an actual student. The second column probably needs to be DateOfContact.
A primary key {StudID, DateOfContact} allows one contact per student per day. If you use {StudID, TimeOfContact} instead--use a timestamp instead of a date--you can have more than one contact per student per day.
In addition to that, if every row in tblContact must refer to both a student and to one of that student's courses, then you should probably include CourseID in the primary key. You also need a foreign key reference from tblContact (StudID, CourseID) to tblStudentCourse (StudID, CourseID).
If it's not necessary for every row in tblContact to refer to a course, then tblContact.CourseID should be nullable, and it shouldn't be part of the primary key. But you should still have a foreign key reference from tblContact (StudID, CourseID) to tblStudentCourse (StudID, CourseID).

Resources