简体   繁体   中英

SELECT sql with four different tables with primary key and foreign key

For my database, having these four table

First one, DEPARTMENT

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

Second one, EMPLOYEE

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

Third, PROJECT

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

Fourth, WORKSON

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

So my output should be something like

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

Display 0 because the employee has no project to works on.

my currently statement using

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

no idea how should it select

您需要使用GROUP BY和JOINS,以实现您的输出

You should use an left join like this. You only need 2 tables employee and workson .

Try this query:

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

Use this :)

With the given output you do not need to join all the tables, and this could be done by joining employee and works on as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM