2011-06-15 62 views
0

我在數據庫中有三個表。使用連接選擇不同的行

旅館

hostel_id int, 
hosteltype_id int, 
hostelname varchar(100) 
address varchar(800) 

hosteltypes

hosteltype_id int, 
Hosteltypename varchar(100) 

HostelRooms酒店在旅館

1 1 hostel1 address1 
2 1 hostel2 address2 
3 2 hostel3 address3 
4 2 hostel4 address4 
room_id int, 
hostel_id int, 
Room_no int, 
available_beds int 
reserver int 

數據在hosteltype

1 boyshostel 
2 ladieshostel 

在hostelroom

1 1 101 4 4 
2 1 102 4 2 
3 1 103 4 4 
4 2 100 4 4 
5 2 101 4 1 
6 3 101 4 4 

我可以使用命令選擇的行。

select Hostel.hostel_id, Hostel.hostelname, Hostel.address, hosteltypes.Hosteltypename, 
from Hostel,hosteltypes 
where Hostel.hosteltype_id=hosteltypes.hosteltype_id 
and hostel_id = (
       select distinct hostelrooms.hostel_id 
       from hostelrooms 
       where hostelrooms.hostel_id=Hostel.hostel_id and   hostelrooms.hostelrooms>hostelrooms.reserver 
    ) 

i want data similar like 
1 hostel1 address1 boyshostel 
2 hostel2 address2 boyshostel 

如何創建一個類似於上面使用連接語句返回特定hostelid,hostelname,hosteltype SQL命令,其中可用的空間。

+0

你們是不是要檢索特定旅館,這是類型,它的房間? LEFT或INNER將這些表連接在一起很容易,但是您究竟想要達到什麼目的? – slugster 2011-06-15 10:50:08

+0

是的,我試圖找回特定的旅館類型。 – 2011-06-15 12:09:40

回答

0

您錯過了SQL中的from子句。它應該是這樣的:

SELECT Hostel.hostel_id, Hostel.hostelname, Hostel.address, hosteltypes.Hosteltypename 
FROM Hostel 
JOIN hosteltypes ON (hosteltypes.hosteltype_id = Hostel.hosteltype_id) 
JOIN hostelrooms ON (hostelrooms.hostel_id = Hostelhostel_id) 
0

假設你正在試圖獲得旅館與在HostelRooms酒店表項,這樣,就可以明顯的列表..

select distinct (Hostel.hostel_id, Hostel.hostelname, Hostel.address,)hosteltypes.Hosteltypename, 
from Hostel,hosteltypes,hostelrooms 
where Hostel.hosteltype_id=hosteltypes.hosteltype_id 
and hostel_id = hostelrooms.hostel_id