使用桥接连接表

时间:2014-01-25 16:12:38

标签: php mysql database

我需要一些MySQL的帮助。 Db是给了我的,不幸的是我不能以任何方式改变它的结构。

我需要提取属于特定组的员工列表(例如group_id = 2)。我使用网桥连接多个表格并不是很好。你可以帮我一把吗?

+---------------+
|employees      |
+---------------+
|employee_id    |
|FirstName      |
|LastName       |
+---------------+

+-------------------------------+
|employees_department           |
+-------------------------------+
|employee_id                    |
|department_id                  |
+-------------------------------+

+--------------+
|departments   |
+--------------+
|deparmtent_id |
|name          |
+--------------+

+--------------------------------+
|department_groups               |
+--------------------------------+
|group_id                        |
|department_id                   |
+--------------------------------+

+---------------+
|groups         |
+---------------+
|group_id       |
|group_name     |
+---------------+

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

 SELECT e.FirstName, e.LastName       
 FROM department_groups AS dg
 JOIN employees_department AS ed ON (ed.department_id = dg.department_id)
 JOIN employees AS e ON (e.employee_id = ed.employee_id)
 WHERE dg.group_id = 2

答案 1 :(得分:0)

此查询应该可以解决问题:select * from employees, employees_department, department_groups, groups WHERE employees.employee_id = employees_department.employee_id and employees_department.department_id = department_groups.department_id and department_groups.group_id = groups.group_id and groups.group_id = 2

请注意,如果group_id不是整数,则会失败。您可能需要更改最后一位groups.group_id = '2'