Join tables, foreign key

I have 2 tables, staff and departments.

department - id, department

Employees - id, department_id, name and heap are more here.

therefore employee.department_id is a foreign key for department.id

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

Is it 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'm not sure ... you can see my request in the picture.

+6
source share
5 answers

Your friend told you the truth: p

You just need to use the inner join between your two tables:

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

You need to adapt your field to get the desired result :)

+10
source
 SELECT employees.id, employees.department_id, employees.name, departments.department FROM employees INNER JOIN departments ON employees.department_id = departments.id 
+3
source

You should not use SELECT * and just take the fields that you really need only if you need to take a screenshot of the table values.

Like SELECT department.name

0
source

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 
0
source
 SELECT employees.*, department.department FROM employees INNER JOIN department ON employees.department_id = department.id 
0
source

Source: https://habr.com/ru/post/910523/


All Articles