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.)
Related
I'm trying to understand something about the foreign key of a database.
I couldn't find a clear answer for this.
The definition of a foreign key goes something like this,
"Foreign key is a field or a group of fields in a table that refers to the primary key of another table"
OK I get that.
Then we learn about types of relationships we can have among tables using foreign keys.
In one-to-many(1:M) and many-to-many(M:N) relationships, there are duplicates in the foreign key.
But how can this be?
If a foreign key refers to a primary key and a primary key can't have duplicates, how can a foreign key can?
I'm confused.
Can someone please explain this to me?
Note - I'm expecting a common answer, not a DBMS specific one.
For example:
There is an employee table with a primary key column called EmployeeID. There is also a foreign key called SupervisorID, which references a different row in the same table.
Two employees work for the same supervisor. They will have different values in the EmployeeID field, but the same value in the SupervisorID field.
This example uses a reference back to the same table, but the concept is the same when the foreign key references a different table.
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
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.
should I signal the foreign key in a database column name?
FKOrder vs. FK_Order vs. Order
The short answer is no - don't put "FK" in column names of foreign key columns. You can still signal the intent of the column though, here's how I do it:
Naming foreign key columns
It depends on your naming convention for the target of the FK. If you have Id, then I'd prepend the table name when creating FK columns.
Example 1:
For table User with PK Id and table Workitem with user ID FK, I'd call the column Workitem.UserId.
If there were more than one FK between the same tables, I'd make this clear in the column name:
Example 2:
For table User with PK Id and table Workitem with "assigned to user ID" and "created by user ID" FKs, I'd call the columns Workitem.CreatedByUserId and Workitem.AssignedToUserId.
If your naming convention for PKs is more like UserId, then you'd factor that into the above examples so as not to end up with UserUserId.
Naming foreign key constraints
This is mine:
FK_childtablename_[differentiator]parenttablename
The differentiator is used when there is more than one FK between the same two tables (e.g. CreatedByUserId and AssignedToUserId). Often I use the child table's column name for this.
Example 1:
Given tables: Workitem and User
Where User has CreatedByUserId and AssignedToUserId
Foreign key names are FK_Workitem_User_CreatedByUser and FK_Workitem_AssignedToUser
I use double-underscores if tables/columns have underscores in the name:
Example 2:
Given tables: work_item and user
Where user has created_by_user_id and assigned_to_user_id
Foreign key names are FK_work_item__created_by_user and FK_work_item__assigned_to_user
Is usual to name the foreign key fields with an ID (IDORDER, IDPERSON, ...), if you have a table called PERSONS and another CITIES, if one person is in certain city, CITIES has an IDCITY field (K), PERSONS has a IDPERSON (K), and other field IDCITY (FK).
Hope this answers your question. I mean, a foreign key is only foreign when it's in other table, but not in theirs. But it's a good practice to name always the same to the same fields, even if they are in other tables, as a foreign key.
You shouldn't.
If a column becomes a foreign key later, you will have to change the column name, breaking all the scripts that are using it.
If there are multiple foreign keys, you don't know which column belongs to which key, so the only information you gain is that the column is a foreign key, but you already know it by looking at the keys.
Usually I name the foreign key column the same as the primary key, so I know immediately where the key maps.
I normally use the same name as the referenced column in the table holding the FK.
Only if this is potentially confusing (or a column with this name already exists, say id), would I be more explicit. In such a case, adding the entity type name before the rest - say ProductId.
My style is slightly different:
fk_table_column
eg: fk_user_id that is foreign key to User table on id column. I do not use any capital latter.
What is the difference between linking two tables and then the PK is an FK in the other table, but the FK has not got the primary key option (so it does not have the gold key),
and having the PK in one table as a PK in another table?
Am I right to think that the second option is for a many-to-many relationship?
Thanks
FK means that any value in our table should be present in the foreign table.
Since the column in the foreign table should be declared as a PK or a UNIQUE key, this means it can be present only once in the foreign table.
PK means that any value in our table should be present only once.
Combined together, they mean that any value should be present only once both in our table and in foreign table.
This is a (0-1):1 relationship.