平均和比较左连接MySQL

时间:2016-03-02 18:15:56

标签: php mysql sql average

我正在尝试从两个不同的MySQL表中获取信息。

主要表格是这样的:

primary sql table

从这一点开始,我使用这些信息来获得平均费率:

rating sql table

如何编写一个SQL查询,通过计算average的所有行来获得rating_house = house_id评级,并按最高评级对其进行排序,如果评分相同,则评分最高

这就是我自己想出来的:

$sql = "SELECT l.location_address, "
            . "r.rating_structure+r.rating_inventory+r.rating_service/3 AS average "
            . "FROM houses h "
            . "LEFT JOIN rating r ON h.house_id = r.rating_house "
            . "LEFT JOIN location l ON h.house_address = l.location_id "
            . "WHERE h.house_deleted IS NULL SORT BY average DESC LIMIT 10";
$result = $db_connect->prepare($sql);
if($result->execute()){
    while($user_data = $result->fetch(PDO::FETCH_ASSOC)){
        $user_data['location_address']."<br>";
    }
}

但是我没有输出?

2 个答案:

答案 0 :(得分:0)

对于性能,如果您知道相关的行必须存在,请使用INNER JOIN而不是LEFT JOIN。

SELECT l.location_address,
       (SUM(r.rating_structure)+SUM(r.rating_inventory)+SUM(r.rating_service))/3 AS average 
FROM houses h
INNER JOIN rating r ON h.house_id = r.rating_house
INNER JOIN location l ON h.house_address = l.location_id 
WHERE h.house_deleted IS NULL 
GROUP BY l.location_address
ORDER BY 2, 
         (SUM(r.rating_structure)+SUM(r.rating_inventory)+SUM(r.rating_service)) DESC
LIMIT 10

答案 1 :(得分:0)

以下查询应返回按平均评分排序的房屋:

select h.house_id, (sum(hr.rating_structure) + sum(rating_inventory) + sum(rating_service))/3 as "average"
from house h left outer join house_rating hr on h.house_id = hr.rating_house
group by h.house_id
order by average