2017-05-31 35 views
1

我正在學習sql並試圖弄清楚如何將3個表中的數據合併到一個查詢中。我有3個表TASK,PROJECT和PRIORITY_TYPE。當表具有唯一值時查詢顯示重複項?

TASK使用唯一編號task_id列出了數據庫中的所有任務,表示該任務對應於哪個項目的project_id,以及表示該緊急程度的數字的priority_type_id。

PROJECT是所有項目的列表,已完成或未完成。

PRIORTY_TYPE將所有priority_type_id列出爲具有相應priority_type_name的數字,表示緊急性。每個項目的數字都不相同(1個項目中的URGENT與另一個項目中的URGENT不具有相同的priority_type_id)。我想選擇不完整/正在進行的項目的所有任務及其相應的緊急事件。我現在有查詢

select task.task_id, task.project_id, task.priority_type_id 
from task 
where task.project_id in (select project_id from project where completion < 100) 

這顯示從殘缺/正在進行的項目的所有任務以自己特有的TASK_ID的,它們對應於該項目,並在priority_id的數量PRIORITY_TYPE查找。

但是,我還想從select中的PRIORITY_TYPE表中包含priority_type_name。我嘗試看起來像下面的查詢:

SELECT task.task_id, task.project_id task.priority_type_id, priority_type.priority_type_name 
FROM task, priority_type 
WHERE task.project_id IN (SELECT project_id FROM project WHERE completion < 100) 

然而,這會產生帶有重複TASK_ID但不同priority_type_name重複任務,即使每個TASK_ID只在任務中出現一次。任何人都可以在這個方向上指出我的正確方向嗎?

+0

[不良習慣踢:使用舊式連接 - 伯特蘭·亞倫(HTTP:// sqlblog .com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx) – SqlZim

+0

它不會產生重複。它只是產生一個語法錯誤。 – Strawberry

+0

定義priority_type和任務表之間的連接條件。 – YuVi

回答

0

這是因爲它做笛卡爾產品。連接鍵未定義。

查詢應該是這樣的:使用

SELECT task.task_id, task.project_id task.priority_type_id, priority_type.priority_type_name 
FROM task, priority_type 
WHERE task.project_id IN (SELECT project_id FROM project WHERE completion < 100) 
and task.project_id = priority_type.project_id 
0

inner join代替:

select 
    task.task_id 
    , task.project_id 
    , task.priority_type_id 
    , priority_type.priority_type_name 
from task 
    inner join priority_type 
    on task.priority_type_id = priority_type.priority_type_id 
where task.project_id in (select project_id from project where completion < 100) 
相關問題