Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining tables using foreign key

Tags:

join

mysql

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 name, so in place of department_id, i need to place departments.department.

How should I do this?

like image 325
Jordashiro Avatar asked Mar 12 '12 16:03

Jordashiro


People also ask

Can you join tables with foreign keys?

A foreign key is a column or group of columns in one table that contains values that match the primary key in another table. Foreign keys are used to join tables.

Do you need foreign keys for JOINs?

Joins are defined using foreign keys only. Of course, you might not define the foreign key in the database. Using foreign key will better the performance (provided the foreign key selection is right).

Are JOINs faster with foreign keys?

Foreign keys do not directly speed up the execution of queries. They do have an indirect effect, because they guarantee that the referenced column is indexed. And the index will have an impact on performance. As you describe the problem, all the join relationships should include the primary key on one of the tables.

Can foreign key refer to two tables?

A foreign key is a key used to link two tables together. This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.


2 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 :)

like image 111
Anthony Avatar answered Oct 14 '22 07:10

Anthony


SELECT employees.id, employees.department_id, employees.name, departments.department
FROM employees
INNER JOIN departments ON employees.department_id = departments.id
like image 29
Ryan Kempt Avatar answered Oct 14 '22 08:10

Ryan Kempt