'我有一個數據庫,員工被分配到不同的項目。有些項目分爲不同的任務。以下數據庫結構已創建。'加入具有相同外鍵的多個表
USER:
+------------+-------------+
| Person ID | Name |
+------------+-------------+
| 1 | A |
| 2 | B |
| 3 | C |
+------------+-------------+
PROJECT_ASSIGNMENT:
+-----------------+-------------+-----------+
| P_Assign key | Project Key | Person ID |
+-----------------+-------------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
+------------+-------------+------+-----+----
TASK ASSIGNMENT:
+-----------------+-------------+-----------+--------+
| T_Assign key | Project Key | Person ID |task key|
+-----------------+-------------+-----------+--------+
| 1 | 2 | 1 | 1 |
| 2 | 2 | 2 | 1 |
| 3 | 2 | 3 | 1 |
| 4 | 2 | 1 | 2 |
| 5 | 2 | 2 | 2 |
| 6 | 2 | 3 | 2 |
+------------+-------------+------+-----+------------+;
'What type of query would be required to get results like this?'
+-----------------+-------------+-----------+
| Person ID | Project Key | Task Key |
+-----------------+-------------+-----------+
| 1 | 1 | NULL |
| 1 | 2 | 1 |
| 1 | 2 | 2 |
| 2 | 1 | NULL |
| 2 | 2 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | NULL |
| 3 | 2 | 1 |
| 3 | 2 | 2 |
+------------+-------------+------+-----+---+
我已經嘗試了一些查詢,但我認爲有相同的外鍵防止我得到我需要的結果。
SELECT
user.person_ID,
task_assignment.Project Key,
project_assignment.Project Key
FROM user
JOIN dbo.project_assignment
ON project_assignment.person_key=user.person_key
LEFT JOIN dbo.task_assignment
ON dbo.project_assignment.person_key=dbo.task_assignment.person_key
如果一個項目被分成任務,該人被分配到該任務。 如果某個項目未分解成任務,則該人被分配到該項目。
你嘗試過什麼?請包括示例代碼來證明您已經付出了一些努力來解決此問題。 – nrussell 2014-08-29 18:26:45