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?
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.
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).
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.
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.
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 :)
SELECT employees.id, employees.department_id, employees.name, departments.department
FROM employees
INNER JOIN departments ON employees.department_id = departments.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With