MySQL 使用外键连接表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9670898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:28:56  来源:igfitidea点击:

Joining tables using foreign key

mysqljoin

提问by Jordashiro

I have 2 tables , employees and departments.

我有 2 个表,员工和部门。

departments(id, department)

部门(ID,部门)

employees(id, department_id, name, and a bunch more here)

员工(id,department_id,姓名,还有更多在这里)

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

所以employees.department_id 是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.

我需要显示表员工,但不是department_id(显示部门的ID),我需要显示实际的部门名称,所以代替department_id,我需要放置departments.department。

How should I do this?

我该怎么做?

回答by Anthony

Your friend told you the truth :p

你的朋友告诉了你真相: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 :)

您必须调整您的领域以获得所需的输出:)

回答by Ryan Kempt

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

回答by Michael Laffargue

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.

SELECT *如果只是为了截取表值的屏幕截图,则不应使用并仅获取您真正想要的字段。

Like SELECT department.name

喜欢 SELECT department.name

回答by Jeremy Pridemore

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

回答by St.Woland

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