选择多个表的平均值

时间:2016-05-11 08:33:04

标签: mysql average

我有以下查询:

"SELECT
    bnbs.name,
    bnbs.slug,
    bnbs.city,
    bnbs.website,
    bnbs.description,
    bnbs.profile_picture,
    bnbs.price_low,
    (SELECT AVG(ROUND((ratings.rating_room+ratings.rating_cleanliness+ratings.rating_service+ratings.rating_meals+ratings.rating_general)/5)) FROM ratings) AS average
FROM
    bnbs
        JOIN
            accounts
                ON
                    bnbs.account_id = accounts.account_id
WHERE
    bnbs.average = 3
AND
    bnbs.visible = 1
AND
    accounts.active = 1
AND
    accounts.confirmed = 1";

当我删除时," bnbs.average = 3"在where clausule中,查询有效,但我想从 ALL 计算表评级中每个bnb的评级的平均评分(每个bnb可以有多个评级),我想要选择评级= 3或>的所有bnbs。 3,或4,......我想你明白了。

有人有想法吗?

1 个答案:

答案 0 :(得分:0)

选择列表中的average字段是计算字段,不是bnbs表的一部分,因此mysql可能会给您一个未知的字段错误。计算字段可以在having子句中过滤,而不是在where子句中过滤。

SELECT
    bnbs.name,
    bnbs.slug,
    bnbs.city,
    bnbs.website,
    bnbs.description,
    bnbs.profile_picture,
    bnbs.price_low,
    (SELECT AVG(ROUND((ratings.rating_room+ratings.rating_cleanliness+ratings.rating_service+ratings.rating_meals+ratings.rating_general)/5)) FROM ratings) AS average
FROM
    bnbs
        JOIN
            accounts
                ON
                    bnbs.account_id = accounts.account_id
WHERE
    bnbs.visible = 1
AND
    accounts.active = 1
AND
    accounts.confirmed = 1
HAVING average = 3

但是,选择列表中的子查询计算所有bnbs记录的相同平均值,因为我没有看到其中的任何标准。您还可以删除子查询并在连接列表中添加评级表并使用group by。在这种情况下,您仍然需要在having子句中过滤您想要查看的平均值。