下面的选择查询返回1行,应该是3.我很确定这是因为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));
答案 0 :(得分:0)
你遇到了MySQL的一个陷阱:
http://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html
我讨厌MySQL曾经允许这种语法,因为它只会引起混淆。但你可能想要的是(使用MySQL的hackish行为,请注意,如果除engine_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的hackish行为:
$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";