2014-04-26 160 views
0

對於我的數據庫中四個不同的表,具有這4臺選擇SQL與主鍵和外鍵

首先一個,部門

//DEPARTMENT 
D#  DNAME 
------------------ 
1  RESEARCH 
2   IT 
3  SCIENCE 

第二個,員工

//Employee 
E#  ENAME   D# 
----------------------- 
1  ALI   1 
2  SITI   2 
3  JOHN   2 
4  MARY   3 
5  CHIRS   3 

三,PROJECT

//PROJECT 
P#  PNAME  D# 
----------------------- 
1  Computing  1 
2  Coding  3 
3  Researching 3 

四,WORKSON

//WORKSON 
E#  P#  Hours 
-------------------- 
1  1  3 
1  2  5 
4  3  6 

所以我的輸出應該是這樣的

E#  ENAME  D#  TOTAL HOURS/W 
-------------------------------------------- 
1   ALI  1    8 
2  SITI  2    0 
3  JOHN  2    0 
4   MAY  3    6 
5  CHIRS  3    0 

顯示0,因爲員工沒有項目運作上。

我目前使用

SELECT E#,ENAME,D# and sum(Hours) as TOTAL HOURS/W 
    FROM EMPLOYEE,PROJECT,WORKSON 
    WHERE EMPLOYEE.P# 

不知道語句應該怎樣選擇

+0

究竟你的錯誤是什麼? – Sadikhasan

+0

爲什麼你有MySQL,SQL Server和Oracle的標籤? –

+0

由stackoverflow建議 – user3553846

回答

0

你應該使用左連接喜歡這個。您只需要2個表employeeworkson

嘗試此查詢:

SELECT e_tbl.E#, e_tbl.ENAME, e_tbl.D#, 
coalesce(SUM(w_tbl.Hours), 0) as "Total Hours/W" 
FROM 
EMPLOYEE e_tbl LEFT JOIN WORKSON w_tbl 
ON e_tbl.E# = w_tbl.E# 
GROUP BY e_tbl.E# 
+0

你的代碼缺少表達式...... – user3553846

+0

this:'GROUP BY e_tbl.E#'??? – CodeBird

+0

ya。你的代碼應該顯示所有員工。但我讀到的只是顯示具體的E#只是不是 – user3553846

0

您需要使用GROUP BY和連接,以達到你的輸出

0
SELECT E.E#, 
     E.ENAME, 
     E.D#, 
     sum(Hours) AS TOTAL HOURS/W 
FROM Employee AS E 
JOIN WORKSON AS W ON E.E# = W.E# 
GROUP BY E.E#, 
     E.ENAME,E.D# 

使用此:)

0

在給定的輸出,你不需要加入所有的表,而這可以通過參加員工和工作完成作爲

select 
e.`E#`, 
e.ENAME, 
e.`D#`, 
coalesce(tot,0) as `TOTAL HOURS/W` 
from Employee e 
left join 
(
    select `E#`, 
    sum(Hours) as tot 
    from WORKSON 
    group by `E#` 
)w 
on w.`E#` = e.`E#` 
group by e.`E#` 

DEMO