How can i save multiple foriegn key value in my table? - sql

I have two tables. Teacher and student. The teacher table consist with id, name, classid, studentId. In student table consist of id, name, TeacherId.
One student can have more than one teachers. And the teacherid is set as foreign key in student table. Then how can I save my student table with multiple teacherid?

If a student can have multiple teachers then you can't put the teacher ID in the student table. You need a third table that contains the combinations of student ID and teacher ID. That way, one student record can be related to multiple teachers and each teacher can be related to multiple students. A third table is how you implement a many-to-many relationship.

You can have a separate table with student and teacher mapping. So, that a single student id could be mapped with multiple teacher ids and you can also have date range or deactivation columns to change your mappings.

Relationships between entities in relational databases are commonly divided into 3 types. This is called the cardinality of the relationship:
1 to N: For example an order (1) with it's products (N). In this case the product would have the order's key.
1 to 1: For example a teacher (1) with it's contact info (1). This type of relationships might raise an eyebrown since you could put the contact's info inside the teacher's table. In this case either the contact has the teacher's key or the teacher has the contact's key (or both share the same exact key).
N to M: Like in your case, a particular teacher may have more than 1 student and each of those students might have another teachers. You can't store this relationship in 2 tables (not in a good way at least), so the solution is creating a 3rd table that links the two.
For this last case, you would have something like the following:
CREATE TABLE Teacher (
TeacherID INT PRIMARY KEY,
-- Other teacher columns
)
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
-- Other student columns
)
CREATE TABLE TeacherByStudent (
TeacherID INT,
StudentID INT,
PRIMARY KEY (TeacherID, StudentID),
FOREIGN KEY (TeacherID) REFERENCES Teacher (TeacherID),
FOREIGN KEY (StudentID) REFERENCES Student (StudentID))

Better you should following tables
Student
Id (Primary Key)
Name
Teacher
Id (Primary Key)
Name
ClassId (Foreign Key)
TeacherStudentMapping
Id (Primary Key)
StudentId
TeacherId
Set Unique Key for StudentId & TeacherId.

Related

Record in one table unique to a record in another table

Let me try to make it simple with an example.
I am creating a database with 2 tables, School and Students
School table with 2 columns SchoolID(PK) and Location
Student table with 3 columns StudentID(PK), SchoolID(FK) and Grade
The Student table will have students from all the schools which can be identified by the foreign key SchoolID. The StudentID column will be unique to each student across all schools. Well and good so far.
I need another column in Student table which will be unique only with respect to the foreign key value. Let's call this ID. I need this column to be unique only to each SchoolID. So, If I filter out the students belonging to a particular SchoolID, I shouldn't get 2 students with same ID.
I'm not sure if that's a valid scenario.
Edit:
This is good
This is not
I think there is something wrong with the datamodel. Since you have StudentID as primary key in Student-table, this column will always be unique in this table. But it seems like you are trying to create a Student-School table where you can have the same student connected to multiple schools (but no the same school multiple times for one single student). I think you need at least 3 tables:
Student (Pk StudentID)
School (Pk SchoolId)
StudentSchool
The StudentSchool table will have two FK-columns: StudentID and SchoolID. To protect from the same student beeing mapped to the same school multiple times you could either have the PK include StudentId and SchoolId or create a Unique constraint.

Simple SQL Multi-Table Design

Lets say I have a table of Classrooms.
Classroom Table
Each Classroom has its own set of Students specific to that Classroom. What would be the best way to set this up? Should I…
A. Make a separate Student table for each Classroom? How would I assign a Classroom to a table though?
B. Make one big list of Students each with their own Classroom FK? What if there are millions of Students and you are only looking for Students of a specific Classroom?
I am new to SQL btw
I would suggest one table for each entity and a join table to describe the relationship between the two. So one table for all the students, another table for all the classrooms and another table for joining.
Minimal example
STUDENT table has columns id (integer, primary key) and name (varchar).
CLASSROOM table has columns id (integer, primary key) and description (varchar).
STUDENT_CLASSROOM has integer columns id (primary key), student_id and classroom_id.
This way students can be assigned to classrooms (or classrooms can be assigned to students) and you can declare your foreign keys as appropriate.

How can you reference multiple rows in another table?

Let's suppose I have a table of roles, for example,
Roles
-----
ID Name
0 Salesman
1 Client
2 Manager
Let's also suppose that these roles are not mutually exclusive: that is, a person can be a salesman, a client, and a manager all at the same time.
If I have a Person table with a Role field, how am I able to reference multiple rows in the Roles table?
You introduce a new table that references both of the original tables:
CREATE TABLE PersonRoles (
PersonID int not null,
RoleID int not null,
constraint PK_PersonRoles PRIMARY KEY (PersonID,RoleID),
constraint FK_PersonRoles_Persons FOREIGN KEY (PersonID) references Person (ID),
constraint FK_PersonRoles_Roles FOREIGN KEY (RoleID) references Role (ID)
)
Assuming that the multiplicity is m:n, the above is correct. I made the assumption (not listed in your question) that more than one person can be e.g. a Salesman.
You have to create another table having (at least) two columns:
PersonId, RoleId
So you can insert (e.g.)
1, 0
1, 2
2, 1
and your Person with id=1 will be a Salesman and a Manager, while Person with id=2 will be a Client.
For this to work, you will need to make a "n-m relation". You need an extra table, eg. called "person_role", that contains foreign keys to both the other tables:
Person <===> PersonRole <===> Role
So you will have 3 tables:
Person
------------
ID
Name
etc.
Role
---------
ID
Name
PersonRole
------------
PersonID
RoleID
You also should make PersonID and RoleID into an unique composite key, to avoid any duplicates
/ Carsten

Weak Entity containing a foreign key as a primary key

I have created a table called STUDENT which consists of Unique ID as the PRIMARY KEY along with other related attributes like Name, Addr, Gender etc....
Since I don't want to increase the table size of the STUDENT, I created a weak entity called ACADEMIC RECORDS which stores the previous Academic Records of the student.But in this table i have only created a PRIMARY KEY Unique ID which references the Unique ID of the student. and there is no other attribute in conjunction with Unique ID in the weak entity ACADEMIC RECORD Table.
As I came across the definition OF A WEAK ENTITY which define its primary key as a combination of weak entity's attribute and the owner's table's primary key(in this case STUDENT)
Is my method of creating a foreign key as the only primary key in the table ACADEMIC RECORD correct??
STUDENT Table
**UID** NAME GENDER ADDRESS PHNO.
ACADEMIC RECORD Table
**UID** HighschoolMarks GradSchoolMarks
There's nothing necessarily wrong with having a primary key that's also entirely a foreign key. It's a common way of implementing something like ‘base classes’, where an entity has a row in a base table, and may have a row in one or more extension tables (one to one-or-zero relationship).
I'm not sure it's the most appropriate schema for what you're doing though. If there really is an exactly one-to-one relationship between academic_records and students, it looks like they are part of the same entity to me.
In which case from a normalisation point of view the record columns should be part of the main students table. Maybe there's an efficiency reason to denormalise, but “I don't want to increase the table size” is not normally an adequate reason. Databases can cope with big tables.
I'm not completely clear on what you are asking, but it sounds like you are using the correct method.
Your STUDENT table requires a primary key to provide a unique reference for each row.
Your ACADEMIC_RECORD table also requires a primary key to provide a unique reference for each row.
Each student may have zero or more academic records, and you want to identify the student to which each academic record belongs. You do this by adding a column in the ACADEMIC_RECORD table which contains the id (the primary key) of the student:
STUDENT ACADEMIC_RECORD
id
id <-------> student_id
name high_school_marks
gender grade_school_marks
address
phone_no
Assume you have three students: Alice, Bob and Dave. Alice and Dave have three academic records, and Bob has two. Your tables would look something like this (I've omitted some columns to make things clearer):
STUDENT
id name
1 Alice
2 Bob
3 Dave
ACADEMIC_RECORD
id student_id
1 1
2 1
3 1
4 2
5 2
6 3
7 3
8 3

Many-to-many relations in RDBMS databases

What is the best way of handling many-to-many relations in a RDBMS database like mySQL?
Have tried using a pivot table to keep track of the relationships, but it leads to either one of the following:
Normalization gets left behind
Columns that is empty or null
What approach have you taken in order to support many-to-many relationships?
Keep track of a many-to-many relationship in a table specifically for that relationship (sometimes called a junction table). This table models the relationship as two one-to-many relationships pointing in opposite directions.
CREATE TABLE customer (
customer_id VARCHAR NOT NULL,
name VARCHAR NOT NULL,
PRIMARY KEY (customer_id));
CREATE TABLE publication (
issn VARCHAR NOT NULL,
name VARCHAR NOT NULL,
PRIMARY KEY (issn));
-- Many-to-many relationship for subscriptions.
CREATE TABLE subscription (
customer_id VARCHAR NOT NULL,
FOREIGN KEY customer_id REFERENCES customer (customer_id),
issn VARCHAR NOT NULL,
FOREIGN KEY issn REFERENCES publication (issn),
begin TIMESTAMP NOT NULL,
PRIMARY KEY (customer_id, issn));
You then use the junction table to join other tables through it via the foreign keys.
-- Which customers subscribe to publications named 'Your Garden Gnome'?
SELECT customer.*
FROM customer
JOIN subscription
ON subscription.customer_id = customer.customer_id
JOIN publication
ON subscription.issn = publication.issn
WHERE
publication.name = 'Your Garden Gnome';
-- Which publications do customers named 'Fred Nurk' subscribe to?
SELECT publication.*
FROM publication
JOIN subscription
ON subscription.issn = publication.issn
JOIN customer
ON subscription.customer_id = customer.customer_id
WHERE
customer.name = 'Fred Nurk';
I would use a pivot table, but I don't see where your issues are coming from. Using a simple student/class example:
Student
-------
Id (Primary Key)
FirstName
LastName
Course
------
Id (Primary Key)
Title
StudentCourse
-------------
StudentId (Foreign Key -> Student)
CourseId (Foreign Key -> Course)
Or, as somebody else mentioned in response to your Student/Teacher/Course question (which would have an additional table to store the type of person in the course):
PersonType
----------
Id (Primary Key)
Type
Person
------
Id (Primary Key)
FirstName
LastName
Type (Foreign Key -> PersonType)
Course
------
Id (Primary Key)
Title
PersonCourse
------------
PersonId (Foreign Key -> Person)
CourseId (Foreign Key -> Course)
The Student table contains student information, the Course table stores course information...and the pivot table simply contains the Ids of the relevant students and courses. That shouldn't lead to any null/empty columns or anything.
In addition to Justin's answer: if you make clever use of Foreign Key constraints, you can control what happens when data gets updated or deleted. That way, you can make sure that you do not end up with de-normalized data.