【问题标题】:select where average with multiple tables选择多个表的平均值
【发布时间】:2016-05-11 08:33:03
【问题描述】:

我有以下疑问:

"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";

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

有人有想法吗?

【问题讨论】:

  • 我不明白这一点。一些正确的 CREATE 和 INSERT 语句和期望的结果的任何机会?
  • 每个 bnb 的评分存储在单独的表(评分)中。想要选择平均评分(例如,一个 bnb 可以有多个评分 - 每个评分连续)为 3 或 4 的所有 bnb。

标签: mysql average


【解决方案1】:

选择列表中的average字段是计算字段,不是bnbs表的一部分,所以mysql很可能给你一个未知字段错误。计算字段可以在have子句中过滤,而不是在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 记录计算相同的平均值,因为我在其中看不到任何 where 条件。您还可以删除子查询并在联接列表中添加评级表并使用分组依据。在这种情况下,您仍然需要在 having 子句中过滤您想要查看的平均值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2017-02-06
    • 2021-07-27
    • 2013-03-17
    • 2021-07-08
    相关资源
    最近更新 更多