我想从3个不同的表中选择不同的列并在表数据中显示。
我有一个名为room的表。因为我有两个外键,分别称为Hotel_id和Room_Type_id。房间表中的其他列是价格,设施等。我想使用FK hotel_id从酒店表中获取hotel_name,并使用FK Room_Type_id从room_type表中获取room_type_name。
我脑筋急转弯,并使用联接分别查找hotel_name和room_type_name进行查询。使用以下查询
//Query to find hotel_name
$query = "SELECT hotels.hotel_name FROM hotels INNER JOIN room ON room.Hotel_Id=hotels.hotel_id";
$res = mysqli_query($connection, $query);
while ($data1 = mysqli_fetch_array($res)) {
//Query to find room_type_name:
$sel_cus = "SELECT room_type.Room_Type_Name FROM room INNER JOIN room_type ON room.room_type=room_type.Room_Type_Id";
$res_cus = mysqli_query($connection, $sel_cus);
while ($data = mysqli_fetch_array($res_cus)) {
//Query to select price,and picture of room:
$count=1; // counter to print serial numbers in table
$sel_cus = "select * from room Order by room_id ASC";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {
// here is code to print record in table
<tbody>
<tr>
<td><?php echo $count; ?></td>
<td ><?php echo $data1['hotel_name'];?></td>
<td><?php echo $data['Room_Type_Name']; ?></td>
<td><?php echo $row['price']; ?></td>
} // End Query to find hotel_name
} // End Query to find room_type_name:
} // end of Query to select price,and picture of room
上面的代码按照记录位于房间表中的方式迭代hotel_name和room_type_name,当前有2条记录位于房间表中,并且迭代2次,请帮助我解决此问题。
使用上述代码输出:
Sr hotel_name Roomtype price picture
1 ABC Delux 600 a.jpg
2 ABC Delux 600 a.jpg
3 XYZ Super 8000 bcv.jpg
4 XYZ Super 8000 bcv.jpg
I want the output like below
Sr hotel_name Roomtype price picture
1 ABC Delux 600 a.jpg
2 XYZ Super 8000 bcv.jpg
请帮助
答案 0 :(得分:1)
您可以只使用一个查询,例如:
SELECT hotels.hotel_name
, room_type.Room_Type_Name
, room.price
, room.facilities
, room.picture
FROM hotels
INNER JOIN room ON room.Hotel_Id=hotels.hotel_id
INNER JOIN room_type ON room.room_type=room_type.Room_Type_Id
ORDER BY hotels.hotel_name , room_type.Room_Type_Name, room.price