Relationship between two entities in a database - mysql

I have two tables, one named as employee , contains the details of an employee, with the primary keys as employee_id and employee_name.
The other named as assignment, with primary key as assign_id.
Now, there are two columns in the table employee. One is preference_1 and other is preference_2. These both can contain the assign_id from table assignment. Preference 1 has to be filled by all the employees and preference 2 is optional but no more than two preferences should be allowed.
How do I link both these tables ?

preference_1 and preference_2 should be two separate tables, not inside employee table. You can have an employee_ID inside the pref_1, pref_2 AND assignment tables.

Maybe something like this
SELECT e.employee_name, a1.assigment_name AS firstPreference, a2.assignment_name AS secondPreference
FROM employee e
JOIN assignment a1 ON e.preference_1 = a1.assign_id
LEFT JOIN assignment a2 ON e.preference_2 = a2.assign_id

Since, preference_2 is optional; make preference_1 (OR) preference_1/preference_2 foreign keys to assignement's assignment_id. Means, preference_1/preference_2 references assignment(assignment_id).
Talking about the relationship, to me it looks like a many-many relationship; cause a employee may work on multiple assignment and similarly a single assignment may be assigned to more than one employee.
Table creation:
Put NULL constraint for preference_1 since it must be filled by employee; like preference_1 int not null but make preference_2 a nullable column like preference_2 int null.
That will make sure, every employee has at least one assignment. If optional pref_2 is filled then he/she will work on 2 assignment.
While querying, you can do a join like
select e.* from employee e join assignment a on
e.preference_1 = a.assignment_id
and isnull(e.preference_2,0) = a.assignment_id

Related

How to join three tables that linked to one table in MySQL?

How do I join three tables that are all linked to one table?
For example, I need to join a term table, a student table and a course table in a University db.
All these tables are linked to just the section table and none other table, but I need to retrieve data from all three tables.
You will have a key relationship between these tables.
ex: you will have a courseid in Course table and the same as a foreign key reference in Student table.
You should decide on what type of join(INNER, OUTER) you need.
From your requirement:
You need sum of the number of credits selected for each term by students. For this you can use the below query.
select selection.student_id, selection.course_id, selection.term_id, sum(course.credits) from selection
join student on selection.student_id = student.id
join course on selection.course_id = course.id
join term on selection.term_id = term.id
group by selection.student_id, selection.course_id, selection.term_id

Multivalued attributes in MySQL

I am working on a database in MySQL to show multivalued attributes. I am trying to find a way to create a parent and child table. The idea that I am working with is having an employee table and a hobby table. The hobbies in the hobby table would be considered the multivalued attributes since employees can have more than one hobby. My question would be, when creating these tables, should I use 3NF and add a 3 table to show the relation between the two or is there a way to implement this idea with simply two tables. I’m not very familiar with multivalued attributes so I need help creating the tables as far as what kind of keys each would use, as well as the end form. I believe I would need to make it in 3NF form and have the hobbies as the multivalued attribute, but have the hobby id from the hobby table as a primary key and the employee id as another primary key and then making the relational table contain both the employee id and hobby id as foreign keys referencing the other two tables. Any help or suggestions to show multivalued attributes would be greatly appreciated!
You have a table for employees already. It probably has a primary key we'll call employee_id.
You need a table for hobbies. It will need a primary key we'll call hobby_id.
Then, you need a way to relate employees and hobbies many-to-many. That's implemented with a third table, let's call it employees_hobbies. Using a name like that is a good idea, because the next guy to work on your code will recognize its purpose right away.
employees_hobbies should have two columns, employee_id and hobby_id. Those two columns together should be the composite primary key. Then, to confer a hobby on an employee, you add a row to employees_hobbies containing the two id values. If an employee drops a hobby, you delete the row.
If you want a list of employees showing their hobbies, you do this
SELECT e.name, GROUP_CONCAT(h.hobbyname) hobbies
FROM employees e
LEFT JOIN employees_hobbies eh ON e.employee_id = eh.employee_id
LEFT JOIN hobbies h ON eh.hobby_id = h.hobby_id
GROUP BY e.employee_id, e.name
Use LEFT JOIN operations here to keep employees without any hobbies (all work and no play) in your list.
If you want to find the most common five hobbies and the employees doing them, try this
SELECT COUNT(*) hobbycount, h.hobbyname,
GROUP_CONCAT(e.name ORDER BY e.name) people
FROM hobbies h
LEFT JOIN employees_hobbies eh ON h.hobby_id = eh.hobby_id
LEFT JOIN employees e ON eh.employee_id = e.employee_id
GROUP BY h.hobbyname
ORDER BY 1 DESC
LIMIT 5
This way of handling many-to-many relationships gives you all kinds of ways of slicing and dicing your data.
MySQL is made for this sort of thing and handles it very efficiently at small scale and large, opinions to the contrary notwithstanding.
(Avoid putting a surrogate primary id key into your employees_hobbies table. It adds no value.)
mva is not very good for mysql .
and best way to store it depend from price you can pay and accessibility need . if you need index , because database is big , and highly loaded , then possible you will need 2 tables .
employee( id , name )
employee_hobbies ( id , employeeid , hobbyid )
but in simplest case , or if you need good accessibility, you can just add text field to employee table , store there comma separated hobbyid , and then select by FIND_IN_SET() function .
e.q. single table
employee( id , name , MVA VARCHAR(512) )
you need be sure that all ids comma separated will fit into fields , side .
SELECT * from employee where FIND_IN_SET(some_hobbyid , MVA)
advantage of this method is less queries ,
disadvantage - may slower then 1st .
also there is advantages for high load system , when import into sphinx ... but this is another story ...

Mysql Obtaining actual value through FK when Selecting all rows

I need to select * FROM sections and get the column values for every row to fill a JTable. My problem is that my adviserId column on section table is an INT
And because I'm getting the result set of every column on every row, I cannot issue a WHERE clause. I thought of subquery but since Id is different on every row, no predetermined Id can be supplied on WHERE clause.
So If I run my stored procedure, I get just an int value for adviserId instead of the teacher's name.
I have teachers and sections table.
Teacher
id PK INT
lastName
firstName
middleName
isAdviser
status
Sections
id PK
name
adviserId FK-- REFERENCING `id` column ON teacher table
What would be the best approach? I hope you can help.
Thanks.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I've created the final stored procedure based on everyone's suggestion. (THANKS AGAIN all.)
CREATE DEFINER=`root`#`localhost` PROCEDURE `getAllSectionsInfo`()
BEGIN
SELECT
s.`name` AS `Section Name`,
s.`session` AS `Session`,
CONCAT(t.lastName,',',t.firstName,' ',t.middleName) AS Adviser,
s.yearLevel AS `Year Level`,
CONCAT(syStart,'-',syEnd) AS SchoolYear
FROM sections s
INNER JOIN
teacher t on s.adviserId = t.id;
END
Yes I also think the same, that a simple inner join will do your job. Try the below example..
create table JTable as select T.id as Tid,T.lastName,T.firstName,T.middleName,T.isAdviser,T.status,S.id as Sid,S.name,S.adviserId
from Sections as S
inner join Teachers as T on T.id = S.adviserId
You can apply left join here to make sure that you have all records of Section table either related to Teachers data or with null data.
So, now the JTable will have all the columns in that you have put on the selection list.
Below is solution for db data selection
SELECT * FROM sections s INNER JOIN teacher on s.adviserId = t.id

How to merge MySQL columns into one column if there are empty values in the table?

I thought it would be better if I ask you by showing images.
Here is my people table. As you can see, it was a bad design idea. Some people have more than one occupation (writer/actress), so I will use a junction table to make it work, and get rid of people table. My question is, how can I move all of these values from people to my person table, without copying the empty values? (For instance, people_id = 1 contains only a director name and other ones are empty.
The following query adds empty values, too. And I also can't select all all the columns with it.
INSERT INTO person (person_name)
SELECT director_name
FROM people
WHERE people_id < 150000;
My person table. I want to copy all names from people to person table, in person_name column.
Presumably, you want to compare for NULL/blank/whatever:
INSERT INTO person (person_name)
SELECT director_name
FROM people
WHERE people_id < 150000 AND
director_name IS NOT NULL AND
director_name <> '';

Access 2013 multi value field

I'm creating a table for a college major. The table is called major. The columns will be majorID, majorName, and requiredCourses.
In Access how can I make requiredCourses a multivalue field? Required courses will be around 20 courses.
Thank you for your help.
You need to create a one-to-many relationship. The way is is usually done is like this:
You need to create a new table for the courses. Call it course. The table will contain CourseID, CourseName, etc. CourceID will be a primary key of this table
You will need to create another table that will act as a link between your major and your course tables. The table can be called something like majorCourses. The table will contain at least these two fields: majorID and courseID (you can of course add more fields, like dateAdded, isInactive, etc.).
To link your tables you will need to JOIN these tables, like this:
SELECT m.majorID, m.majorName, c.courseID, c.CourseName
FROM major m
INNER JOIN (majorCourses mc INNER JOIN course c ON mc.courseID = c.courseID)
ON m.majorID = mc.majorID