使用内部联接加入4个表

时间:2016-03-27 11:51:13

标签: sql sql-server inner-join

我正在尝试用INNER JOIN而不是AND

写下面的查询
select ph.name, ph.position, d.name, COUNT(app.appointmentId)
from physician ph, works_in w, appointment app, department d
where ph.eid = w.physician 
    and d.did = w.department
    and ph.eid = app.physician
group by ph.eid, ph.name, ph.position, d.name

我试过这种方式,但它有很多错误

select ph.name, ph.position, d.name, COUNT(app.appointmentId)
from physician ph inner join works_in w
    on ph.eid = w.department,
    department d inner join works_in w 
    on d.eid = w.department,
    physician ph inner join appointment app
    on ph.ph.eid = app.physician
group by ph.eid, ph.name, ph.position, d.name

如何使用内部联接正确编写它。

2 个答案:

答案 0 :(得分:2)

首先让我帮你this site that explain all about join syntax's

将您的查询更改为:

select ph.name, ph.position, d.name, COUNT(app.appointmentId)
from physician ph 
inner join works_in w
    on ph.eid = w.department
inner join department d  
    on d.eid = w.department
inner join appointment app
    on ph.ph.eid = app.physician
group by ph.eid, ph.name, ph.position, d.name

联接的语法是:

SELECT <COLUMNS>
FROM <Table>
INNER JOIN <Another_Table>
 ON(<Relations>)
INNER JOIN <Another_table2>
 ON(<Other Relations>

答案 1 :(得分:0)

    SELECT ph.name AS Name, ph.position AS Position,d.name AS Name, COUNT(app.appointmentId) AS Appointment
    FROM physician AS ph INNER JOIN works_in AS w
    ON ph.eid = w.department INNER JOIN department d 
ON  d.eid = w.department INNER JOIN appointment app ON ph.eid = app.physician
    GROUP BY ph.eid,ph.name,ph.position,d.name