我想通过book_id加入5个表。我试过了:
SELECT booked_room_info . * , booking_info . * , hotel_info.name as
hotelname,hotel_info.address as hoteladdress,hotel_info.contact as
hotelcontact , personal_info . *,room_registration.room_name as
roomname,room_registration.price as roomprice,room_registration.price as
roomprice,room_registration.description as
roomdescription,room_registration.image as roomimage
FROM booked_room_info
JOIN booking_info ON booking_info.booking_id = booked_room_info.booking_id
JOIN hotel_info ON hotel_info.id = booking_info.hotel_id
JOIN personal_info ON personal_info.booking_id = booked_room_info.booking_id
JOIN room_registration ON room_registration.hotel_id = booking_info.hotel_id
WHERE booked_room_info.booking_id= 1
但是如果我在booking_id = 1上预订了2个,但它获得了10个结果。我想我应该做一个if条件。如果(booked.room_type && book_info.hotel_id)
相同,那么只从room_registration获取行,但我怎样才能完成它。
booked_room_info
------
id | booking_id | room_type | check_in | check_out
1 | 1 | delux | 2015/1/2 | 2015/1/5
booking_info
---------
id | booking_id | hotel_id | user_id
1 | 1 | 2 | 1
hotel_info
----------
id | name | address | user_id
2 |palm hotel | newyork | 1
personal_info
-------------
id |full_name | address | nationality | booking_id
1 | sushil stha | new york | smth | 1
room_registration
-----------------
id | room_name | price | image | hotel_id | user_id
1 | delux | 1000 |room.jpg | 2 | 1
答案 0 :(得分:1)
您上次加入时出错:
JOIN room_registration ON room_registration.hotel_id = booking_info.hotel_id
您正在使用hotel_id
列加入这些表格。 room_registration
表中可能有5行hotel_id=2
。因此,在加入后,您会收到2*5=10
行而不是预期的行。
所以你应该以不同的方式加入这张桌子
如果您希望从room_registration
表格中加入一行,那么您必须指定更精确的连接条件。
要正确加入room_registration
表,您可以将room_registration_id
列添加到booking_info
表。然后你可以使用:
JOIN room_registration ON room_registration.id = booking_info.room_registration_id
答案 1 :(得分:0)
使用INNER JOIN
,删除重复字段。
SELECT
bri.*,
bi.*,
hi.name AS hotelname, hi.address as hoteladdress, hi.contact AS hotelcontact,
pi.*,
rr.room_name AS roomname, rr.price AS roomprice, rr.description AS roomdescription, rr.image AS roomimage
FROM booked_room_info bri
INNER JOIN booking_info bi ON bri.booking_id = bi.booking_id
INNER JOIN hotel_info hi ON bi.hotel_id = hi.id
INNER JOIN personal_info pi ON bri.booking_id = pi.booking_id
INNER JOIN room_registration rr ON bi.hotel_id = rr.hotel_id
WHERE bri.booking_id = 1