使用单个查询获取多个表列的总和

时间:2015-03-25 09:40:56

标签: php mysqli

我有一个主表酒店及其子表 hotel_food hotel_extras hotel_room 及其参考标识酒店

现在我想获得每个酒店的每个表(hotel_food,hotel_extras,hotel_room)的价格列总和。

现在我正在使用这个

$result = $db->query("SELECT id FROM hotel WHERE id = '.$hotel.'");
if($row = $result->fetch_array(MYSQLI_ASSOC)) {
   $food_result = $db->query("SELECT sum(price) FROM hotel_food WHERE hotel_id = '".$row['id']."'");
   $room_result = $db->query("SELECT sum(price) FROM hotel_room WHERE hotel_id = '".$row['id']."'");
   $extras_result = $db->query("SELECT sum(price) FROM hotel_extras WHERE hotel_id = '".$row['id']."'");
}

有没有办法通过单个查询获得所有表格价格的总和,例如totalFoodPrice,totalRoomPrice,totalExtrasPrice

提前致谢

2 个答案:

答案 0 :(得分:1)

SELECT * FROM
(
 SELECT sum(price) AS totalFoodPrice FROM hotel_food WHERE hotel_id = 1,
 SELECT sum(price) AS totalRoomPrice FROM hotel_room WHERE hotel_id = 1,
 SELECT sum(price) AS totalExtrasPrice FROM hotel_extras WHERE hotel_id = 1
) temp

答案 1 :(得分:1)

您可以使用这样的子查询:

$result = $db->query("SELECT id, 
   (SELECT sum(price) FROM hotel_food WHERE hotel_id = h.id) TotalFoodPrice,
   (SELECT sum(price) FROM hotel_room WHERE hotel_id = h.id) TotalRoomPrice,
   (SELECT sum(price) FROM hotel_extras WHERE hotel_id = h.id) TotalExtraPrice
FROM hotel h WHERE id = '.$hotel.'");