Home » Mysql » Joining tables , foreign key

Joining tables , foreign key

Posted by: admin April 5, 2018 Leave a comment

Questions:

I have 2 tables , employees and departments.

departments – id , department

employees – id , department_id , name , and a bunch more here.

so employees.department_id is a foreign key to departments.id

I need to show the table employees , but instead of department_id ( showing the IDs of the departments ) i need to show the actual departments , so in place of department_id , i need to place departments.department

Is this possible ? Here is a picture of what i want. http://oi44.tinypic.com/xgdyiq.jpg

PS: a friend told me to use join but i am not sure… , you can see my query in the picture.

Answers:

Your friend told you the truth :p

You just have to use a inner join between your two tables like this:

SELECT d.name, e.name, e.email, ... FROM deparments d INNER JOIN employees e ON d.id = e.department_id.

You have to adapt your field to have the desired output 🙂

Questions:
Answers:
SELECT employees.id, employees.department_id, employees.name, departments.department
FROM employees
INNER JOIN departments ON employees.department_id = departments.id

Questions:
Answers:

You should not use SELECT * and just take the fields you really want if it’s only to take a screenshot of the table values.

Like SELECT department.name

Questions:
Answers:

This should cover it for you:

SELECT
    E.Id
    , D.Department
    , E.Name
    -- More stuff
FROM Employees E
INNER JOIN Departments D
    ON D.id = E.department_id

Questions:
Answers:
SELECT employees.*, department.department
FROM employees
INNER JOIN department ON employees.department_id = department.id