2015-05-20 158 views
0

它適用於選擇所有員工部門和相關工作(包括所有部門和工作的所有數據)在一個SQL語句中,每個員工可以關聯到多個部門和作業像下面MYSQL - INNER JOIN返回行數

員工表

+-------------+---------------+ 
| 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 | 
+--------+---------------+-------------------+ 

編輯: 下面是數據的一個例子,我想以檢索:

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', 
    ) 
) 

編輯:

下面是聲明我寫信給這個數組,但它並沒有將部門數據檢索爲ar射線

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' 
+1

如果你的意思是,是否有可能,是的。如果您對模式有任何控制權,似乎您可以從「Jobs」表中刪除「Department ID」列,因爲它已經存在於「Employee Jobs」表中。你有一個具體的查詢,你需要幫助嗎? –

+0

是的。這完全有可能。 –

+0

如果有一個例子,它會很好:) – ahmedsaber111

回答

3

要得到所有你正在尋找的值,你可以參加所有的表一起在諸如主鍵和外鍵關聯列,包括任何你在你的SELECT語句需要。從底部開始,建立自己的方式。

例如,每個job有一個部門,這樣你就可以得到這兩個這樣的信息:通過加入EmployeeJobsEmployee

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

要得到員工的信息,你可以這樣做。

我想指出你有一些正常化問題。在job表中指定作業所屬的部門,employeeJobs內部也不需要有department,因爲您可能會遇到數據庫中的一些異常情況。

-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`