MYSQL - 返回行数组

时间:2015-05-20 19:08:33

标签: php mysql

是否适用于在一个SQL语句中选择所有员工部门和相关工作(包括所有部门和工作的所有数据),其中每个员工可能与多个部门和下面的工作相关联< / p>

员工表

+-------------+---------------+
| Employee ID | Employee Name |
+-------------+---------------+
| 27          | Name          |
| 28          | Name 2        |
+-------------+---------------+

员工职位

+-------------+---------------+--------+-----------+-----------+
| Employee ID | Department ID | Job ID | From      | To        |
+-------------+---------------+--------+-----------+-----------+
| 27          | 1             | 3      | some date | some date |
| 27          | 2             | 7      | some date | some date |
+-------------+---------------+--------+-----------+-----------+

部门

+---------------+-----------------+
| Department ID | Department Name |
+---------------+-----------------+
| 1             | Sales           |
| 2             | Operation       |
+---------------+-----------------+

工作

+--------+---------------+-------------------+
| Job ID | Department ID | Job Name          |
+--------+---------------+-------------------+
| 3      | 1             | Sales Director    |
| 7      | 2             | Technical Support |
+--------+---------------+-------------------+

EDITED: 以下是我想要检索的数据示例:

array(
  '0' => array(
        'department name' => 'name',
        'department ID' => 'id',
        'job name' => 'name',
        'job id' => 'id',
     ),
  '1' => array(
        'department name' => 'name2',
        'department ID' => 'id2',
        'job name' => 'name2',
        'job id' => 'id2',
     )
)

编辑:

这是我为获取数组而编写的语句,但它不会将部门数据检索为数组

SELECT * FROM employees_emp 
INNER JOIN job_history_jhis ON (employeeId_emp = employeeId_jHis)
INNER JOIN departments_dep ON (departmentId_jHis = departmentId_dep)
INNER JOIN jobs_job ON (jobId_jHis = jobId_job)
WHERE employeeId_emp = '27'

2 个答案:

答案 0 :(得分:3)

要获取您要查找的所有值,您可以将所有表连接在相关列(如主键和外键)上,并在select语句中包含所需的任何内容。从底部开始,逐步建立起来。

例如,每个job都有一个部门,因此您可以从这两个部门获取信息:

SELECT j.id, j.jobName, d.id, d.departmentName
FROM jobs j
JOIN department d ON d.id = j.department;

要获取员工信息,您可以加入EmployeeJobsEmployee表格来执行相同操作。

我想指出你有一些正常化问题。在job表中,您指定了作业所属的部门,也不需要在department内部employeeJobs,因为您可能会在数据库中遇到一些异常。

答案 1 :(得分:-1)

SELECT e.*, ej.*, j.`Job Name`, d.`Department Name`
FROM Employees e
LEFT JOIN `Employee Jobs` ej
ON e.`Employee ID` = ej.`Employee ID`
LEFT JOIN jobs j
ON j.`Job ID` = ej.`job ID`
LEFT JOIN Department d
ON d.`Department ID` = ej.`Department ID`