SQL-linking two tables with a third table - mysql

I have two tables Students and Courses.
I have to create a mapping table to link these two tables with a set of information.
For eg: Mary Murphy from **Students ** table is to be linked with Courses table with web designing course that she is taking.
How can I do this??
Thank you in advance.

You would use a third table, studentCourses would be a reasonable name. It would look something like this:
create table studentCourses (
studentCourseId int auto_increment primary key,
studentId int,
courseId int,
constraint fk_studentcourses_student foreign key (studentId) references students (studentId),
constraint fk_studentcourses_course foreign key (courseId) references students (courseId)
);
You might include other information, such as the enrollment date.

Related

Best approach to store 100+ columns in one table in MySQL

I am working on a data model where I need to store Employee's basic details and his rating of skillsets in MySQL database.
The number of skillsets for each employee is more than 100.
So the information I need to store is as following:
Employee ID, Name , Department , Contact info, Skillset1,Skillset2,Skillset3, ... , Skillset115
Is creating one table with approximately 120 columns is good approach?
If not, what is the best practice to deal with this kind of requirement.
No. You should have a separate table with one row per employee and per skill:
create table employeeSkills (
employeeSkillId int auto_increment primary key,
employeeId int not null,
skill varchar(255),
constraint fk_employeeSkills_employeeid foreign key (employeeId) references employees(employeeId)
);
In fact, you should really have two extra tables. The skills themselves should be stored in a separate table and the above should really be:
create table employeeSkills (
employeeSkillId int auto_increment primary key,
employeeId int not null,
skillId int,
constraint fk_employeeSkills_employeeid foreign key (employeeId) references employees(employeeId),
constraint fk_employeeSkills_skillid foreign key (skillId) references skills(skillId)
);
This type of table is called a "junction table", and is common in any properly constructed data model.
You need to create two tables that would handle the skills and the assigned skill for each employee.
This would give you a proper order in your database and also will extend your options in the future. It'll be better in search, add and assign skills to each employee. It's even more organized and would be able to be expanded easily such as adding skills category and sub-category.
The two tables schema should be something like this :
CREATE TABLE Skills (
Skill_ID INT NOT NULL AUTO_INCREMENT,
Skill_Description VARCHAR(250),
PRIMARY KEY (`Skill_ID`)
);
CREATE TABLE EmpolyeeSkills (
ES_ID INT NOT NULL AUTO_INCREMENT,
Skill_ID INT,
Employee_ID INT,
PRIMARY KEY (`ES_ID`),
CONSTRAINT FK_EMPLOYEEID FOREIGN KEY (Employee_ID) REFERENCES Employees(Employee_ID),
CONSTRAINT FK_SKILLID FOREIGN KEY (Skill_ID) REFERENCES Skills(Skill_ID)
);
The Skills table will assign an ID for each skill, and it'll be in a separate table. This will make you have a unique skills list, there won't be any redundancy. Then, you'll use EmployeeSkills to save the assigned skills on each Employee_ID. Which you can use it later on to join it with other records.
The FOREIGN KEY on Employee_ID and Skill_ID will help you in monitoring the skills between them.
The ES_ID primary key for EmpolyeeSkills will be an additional advantage that can be helpful in the future. For instance, if you want to know the latest skill that has been assigned, then your faster approach will be getting the last ES_ID as it's an AUTO_INCREMENT. This is just one advantage from tons of others.

Using an ISA relationship in mysql

i currently have 3 entities. Employees, teachers, and custodians. All teachers and custodians are employees. All employees have an id, name, and email. I have tried connected custodians and teachers to Employees using an ISA relationship with primary and foreign keys. I am attempting to create the tables, so that when i create a "teacher" or a "custodian" the Employee table is also populated. I currently have only an id for teacher/custodian linked to the employee. am i doing this wrong? thank you!
CREATE TABLE employees(
id INT UNSIGNED,
first_name VARCHAR(30),
last_name VARCHAR(30),
email VARCHAR(60),
Primary Key (id));
CREATE TABLE teacher(
teach_id INT UNSIGNED,
)
CREATE TABLE teachemp(
id INT UNSIGNED,
teach_id INT UNSIGNED,
PRIMARY KEY(id,teach_id),
FOREIGN KEY (id) REFERENCES employees(id),
FOREIGN KEY (teach_id) REFERENCES teacher(teach_id)
)
In other words, when i create insert an employee and that employee is a teacher. i want the teacher table to also be populated. am i doing this correctly? or should i create a teacher and the employee table be populated?
Thank you
This is what you need...
Follow this Trigger Example for SQL.
and this Trigger for MYSQL

Adding primary/foreign keys and referencing other tables

Im having some troubles with key referencing. The Error comes from when i try to insert data into Table Mark
INSERT INTO Mark(examID, studentID, result, occured, noOFAttempts)
VALUES ('B10', '1', '67', '11-JUL-07', '1');
I get the error:
integrity constraint violated - parent key
not found
Context :
The tables Exam and Student represent data about college exams and
students. The exam results for the students, including the number of
attempts a student has had at an exam (noOfAttempts), are recorded in
table Mark by using the id column from Exam and the id column from
Student. Both id columns have unique values . A student has only the
latest result recorded for each exam.
Write a SQL command to create the Mark table. Include the primary keys
and foreign keys apparent in the tables specified above.
CREATE TABLE Exam (
id VARCHAR(255),
subject VARCHAR(255),
noOfStudents INT,
PRIMARY KEY (id));
-
CREATE TABLE Student (
id INT,
name VARCHAR(255),
PRIMARY KEY (id));
-
CREATE TABLE Mark (
examID VARCHAR(255),
studentID INT,
result INT,
occured DATE,
noOFAttempts VARCHAR(255),
FOREIGN KEY (noOFAttempts) REFERENCES Exam(id),
FOREIGN KEY (noOFAttempts) REFERENCES Student(id));
How do i fix the error i know its to do with wrong referencing, thanks
Some of the logic behind the Mark table makes sense to me. It relates exams to the students who took those exams. But the motivation to make noOfAttempts a foreign key does not seem to serve much purpose. There are two foreign keys in that table, examID and studentID, and the combination of these two fields is also a primary key. Here is what the Mark definition might look like to avoid these errors:
CREATE TABLE Mark (
examID VARCHAR(255),
studentID INT,
result INT,
occured DATE,
noOFAttempts VARCHAR(255),
FOREIGN KEY (examID) REFERENCES Exam(id),
FOREIGN KEY (studentID) REFERENCES Student(id),
PRIMARY KEY (examID, studentID)
)
Again, I don't see the point of making noOfAttempts a key of any kind, rather I think it should just be one regular column in the Mark table.
Edit per request from Gordon:
When you made your insert, you attempted to create a record in Mark which referred to parent records which did not exist. In the case of your original table, you attempted to insert '1' as the noOfAttempts, but this ID did not exist in either the Exam and/or Student tables.

Self-referential relationship table design: one or two tables?

CREATE TABLE Employee
(
id INT,
boss INT REFERENCES Employee(id),
PRIMARY KEY (id)
);
One employee can have many bosses and one boss can have many employees.
Does this table function the same as this two-table design?
CREATE TABLE Employee
(
id INT,
PRIMARY KEY (id)
);
Create table ManagerRelation (
id_from int NOT NULL,
id_to int NOT NULL,
PRIMARY KEY (id_from, id_to),
FOREIGN KEY (id_from) REFERENCES Employee(id),
FOREIGN KEY (id_to) REFERENCES Employee(id)
);
The second table ManagerRelation stores ids of workers who have boss-employee relationship.
My question is, are these two design right? If right, are they exactly the same functionally?
The two designs are quite different. The first requires that each employee have (at most) one boss, although each boss could have many employees.
The second allows for employees to have more than one boss.
From your description of the problem, the second form is the more appropriate data model. From my understanding of boss-employee relationships, I would expect the first to be correct.

How to create a table that uses a whole other foreign table?

Let's say I have this:
CREATE TABLE `classes`
(
`class_ID` INT AUTO_INCREMENT,
FOREIGN KEY (`student_ID`) references `students`(`student_ID`),
PRIMARY KEY (`class_ID`)
)
ENGINE = InnoDB;
The thing here is that each class refers to a single student. But I want it to refer to a whole other table of students, for example:
CREATE TABLE `students`
(
`student_ID` INT AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`student_ID`)
)
ENGINE = InnoDB;
Hence, I want multiple student tables, which each table associated to a class. How can I do this? Do i have to declare a single table (e.g. students1, students2, etc.) for each class?
Thanks!
The answer to this will be a little difficult to understand at first. After a while it becomes natural. Is is a well-known design pattern. You need a third table:
create table students_in_courses(studentid, courseid)
In this table you have a row for each student and each course that student is in. You can turn this sentence around: A row for each course and each student that is in this course.
It is a "link table". It is used for M:N mappings.
You can think of this table as an entity, just like students and courses. You could even add additional columns:
create table students_in_courses(studentid, courseid, date_entered, date_exited, grade)
A constant number of tables is enough.
Let me try a different explanation: We could store the information which student is in which course by saving a matrix with the students as its rows and the courses as its columns. Every cell has a bool: student is in this course yes/no.
Now we save this entire matrix in a table like this:
create table students_in_courses(studentid, courseid, is_in_course bit) primary key(studentid, courseid)
For each cell a row. Now we delete all rows with is_in_course = 0 and drop that column because it only contains 1's now. We are back at the original solution. Our "link-table" stores the non-zero cells of the cross-product matrix of the two tables.
No. you create a single table that has foreign keys referencing both tables:
CREATE TABLE students_classes (
student_id int,
classes_id int,
PRIMARY KEY (student_id, classes_id),
FOREIGN KEY (student_id) REFERENCES students (student_ID),
FOREIGN KEY (classes_id) REFERENCES classes (class_ID)
);
That way you can have student (example) #7 in classes (#53 and 37 and 83), student #12 in classes (#53, #212, #7), etc... without conflict.