2014-05-23 66 views
0

我不確定我需要什麼類型的JOIN。我有一個表是peoplepeople表具有id,lastname,firstname,title,departmentidphone。 第二個表格是departmentdepartment表具有id,name,roomidtelephone。 第三張表是peopleroomspeoplerooms只有peopleidroomid字段。 第四張表是roomsrooms具有id,nameroomnumberOracle在3個表格上加入2-3個查找

的目標是查詢people和(使用departmentiddepartment表)返回people.idlastnamefirstnametitlename,也room.name使用peoplerooms找到所有房間的peopleid了。

people table 
- id 
- lastname 
- firstname 
- title 
- departmentid 
- phone 

sample people data 
1|smith|will|director|2|555-555-5555 
2|doe|jane|director|3|555-333-4545 

peoplerooms table 
- peopleid 
- roomid 

sample peoplerooms data 
1|10 
2|5 

rooms table 
- id 
- name 
- roomnumber 

sample rooms data 
3|Room C|100C 
5|Room B|100B 
10|Room A|100A 

department table 
- id 
- name 
- roomid 
- phone 

sample department data 
3|Radiology|5|555-454-4444 
2|Billing|3|656-555-6656 

我有以下SQL工作,但我不是在部門名稱拉......我只得到people.departmentid,我需要查找部門,而是讓department.name。

SELECT people.lastname, people.firstname, people.departmentid, people.title, room.roomnumber, people.phone 
FROM room 
JOIN peopleroom ON room.id = peopleroom.roomid 
JOIN people ON peopleroom.peopleid = people.id 
ORDER BY people.lastname 

回答

2

你是正確的道路上。請加入department。嘗試以下查詢。我已經添加people.idroom.name,因爲你在你的問題中提到它:

SELECT 
    people.lastname, 
    people.firstname, 
    people.title, 
    people.phone, 

    room.roomnumber, 
    room.name AS roomname, 

    department.name AS departmentname 

FROM 
    room JOIN peopleroom ON room.id = peopleroom.roomid 
    JOIN people ON peopleroom.peopleid = people.id 
    JOIN department ON people.departmentid = department.id 

ORDER BY 
    people.lastname 
+0

它返回象3分的結果,而不是30的結果是每個部門之一。它以我不需要的方式限制它。 – donlaur

+0

有沒有部門的房間?更具體地說:每個房間都有'room'的'department'條目嗎? –

+0

部門有房間和人有房間。在這個電話會議上,我更關心的是我可以得到每個人的部門名稱。 – donlaur