[英]Get sum of more than one table columns with a single query
I have a main table hotel and its sub tables hotel_food , hotel_extras , hotel_room with the reference Id hotel , 我有一个主表酒店及其子表hotel_food , hotel_extras , hotel_room和参考ID 酒店 ,
And now I want to get the sum of price column in each table (hotel_food, hotel_extras, hotel_room) for each hotels. 现在,我想获取每个酒店的每个表(hotel_food,hotel_extras,hotel_room)中的价格列总和。
Now I am using like this 现在我这样使用
$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']."'");
}
Is there any way to get the sum of all tables prices like totalFoodPrice, totalRoomPrice,totalExtrasPrice with a single query 有没有办法通过单个查询获取所有表价格的总和,例如totalFoodPrice,totalRoomPrice,totalExtrasPrice
Thanks in advance 提前致谢
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
You can make use of the subqueries like this : 您可以使用如下子查询:
$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.'");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.