简体   繁体   中英

Selecting distinct rows using join

I have three table in database.

Hostel

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

data in Hostel

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

in hosteltype

1 boyshostel
2 ladieshostel

in 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

I can select rows using command.

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

how can a create sql command similar to above using join statement which returns specific hostelid,hostelname,hosteltype where the room available.

You're missing the from clause in your SQL. It should be like:

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 )

Assuming you're trying to get a distinct list of hostels with entries in the hostelrooms table, then this should work..

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

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