使用join选择不同的行

时间:2011-06-15 10:45:51

标签: sql sql-server-2008

我在数据库中有三个表。

旅馆

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

hosteltypes

hosteltype_id int,
Hosteltypename varchar(100)

HostelRooms酒店

room_id int,
hostel_id int,
Room_no int,
available_beds int
reserver int

宿舍的数据

1 1 hostel1 address1
2 1 hostel2 address2
3 2 hostel3 address3
4 2 hostel4 address4

在hosteltype

1 boyshostel
2 ladieshostel

在宿舍

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

如何使用join语句创建类似于上面的sql命令,该语句返回特定的hostelid,hostelname,hosteltype所在的房间。

2 个答案:

答案 0 :(得分: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 )

答案 1 :(得分:0)

假设您正在尝试在旅馆客房表中获得一份明确的旅馆列表,那么这应该有用..

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