【问题标题】:Select query returning 1 result instead of 3 because of AVG由于 AVG,选择查询返回 1 个结果而不是 3 个结果
【发布时间】:2014-12-18 15:41:49
【问题描述】:

下面的选择查询在应该是 3 时返回 1 行。我很确定这是因为 AVG(k.sumtotal) 字段。

如果我重写查询并取出 AVG(k.sumtotal) 列并取出 FROM inv_ratings AS k,我会得到 3 行。

我不明白为什么这个表 (inv_ratings) 或这个 AVG(k.sumtotal) 列将行数限制为 1。我在网上看了几个小时试图找到有关使用 AVG 子句返回结果的信息,但没有找不到太多。我是否必须使用 group by 子句,我试过了,但只会出错。

$p = "SELECT i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
    . " i.approved, c.category_id, c.category, u.image_name, AVG(k.sumtotal)"
    . " FROM inv_ratings AS k INNER JOIN inventions AS i USING (invention_id)"
    . " INNER JOIN categories AS c USING (category_id)"
    . " INNER JOIN images AS u USING (invention_id)"
    . " WHERE c.category_id = $cat AND i.approved = 'approved'"
    . " HAVING u.image_name < 2"
    . " ORDER BY date_submitted"
    . " DESC LIMIT $start, $display";

$q = mysqli_query($dbc, $p) or trigger_error("Query: $p\n<br />mysqli Error: " . mysqli_error($dbc));

【问题讨论】:

  • 您需要添加一个GROUP BY 子句。
  • 您想要每个部分的平均值,还是每行都相同的唯一平均值?
  • 你能帮我说一下吗,我试过无数次才能让它工作,但它不会工作
  • 我想要每个发明 ID 的所有评分的平均值。

标签: php mysql average


【解决方案1】:

您遇到了 MySQL 的问题之一:

http://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html

我讨厌 MySQL 曾经允许这种语法,因为它只会引起混乱。但是您可能想要的是(使用 MySQL 的骇人听闻的行为,请注意,如果除发明 ID 或 sumtotal 之外的任何字段有多个值,您会从该列中获得一个随机值):

$p = "SELECT i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name, AVG(k.sumtotal)"
. " FROM inv_ratings AS k INNER JOIN inventions AS i USING (invention_id)"
. " INNER JOIN categories AS c USING (category_id)"
. " INNER JOIN images AS u USING (invention_id)"
. " WHERE c.category_id = $cat AND i.approved = 'approved'"
. " GROUP BY i.invention_id "
. " HAVING u.image_name < 2"
. " ORDER BY date_submitted"
. " DESC LIMIT $start, $display";

或者,不要使用 MySQL 的骇人听闻的行为:

$p = "SELECT i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name, AVG(k.sumtotal)"
. " FROM inv_ratings AS k INNER JOIN inventions AS i USING (invention_id)"
. " INNER JOIN categories AS c USING (category_id)"
. " INNER JOIN images AS u USING (invention_id)"
. " WHERE c.category_id = $cat AND i.approved = 'approved'"
. " GROUP BY i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name "
. " HAVING u.image_name < 2"
. " ORDER BY date_submitted"
. " DESC LIMIT $start, $display";

【讨论】:

  • group by 应该在where 之后。
猜你喜欢
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
相关资源
最近更新 更多