Mysql查询,获取平均结果

时间:2011-06-21 20:59:01

标签: mysql mysqli fetch average

所以我得到了这个查询,是否可以从avgscore获取mysql结果?

SELECT * FROM dog_clinic
LEFT JOIN (SELECT AVG(score) AS avgscore, input_id
FROM dog_clinic_score GROUP BY input_id) s ON s.input_id = dog_clinic.id
ORDER BY avgscore DESC, visited DESC LIMIT 0,10

提前致谢

整个声明:

if ($stmt_dog_clinic = $mysqli->prepare("SELECT dog_clinic.id, dog_clinic.name, dog_clinic.content, dog_clinic.city, dog_clinic.street, dog_clinic.picture, dog_clinic.visited, s.avgscore FROM dog_clinic LEFT JOIN (SELECT AVG(score) AS avgscore, input_id FROM dog_clinic_score GROUP BY input_id) s ON s.input_id = dog_clinic.id ORDER BY s.avgscore DESC, dog_clinic.visited DESC LIMIT 0,10"))
 {
  $stmt_dog_clinic->bind_result($id, $name, $content, $city, $street, $picture, $visited, $avgscore);
  $stmt_dog_clinic->execute();
while ($stmt_dog_clinic->fetch())
{ echo $avgscore; }

$ avgscore ds不会产生任何数据。

2 个答案:

答案 0 :(得分:0)

你的意思是:

SELECT dog_clinic.*, s.avgscore FROM dog_clinic
LEFT JOIN (SELECT AVG(score) AS avgscore, input_id
FROM dog_clinic_score GROUP BY input_id) s ON s.input_id = dog_clinic.id
ORDER BY s.avgscore DESC, dog_clinic.visited DESC LIMIT 0,10;

我认为Rahul是对的,它是隐含的s.avgscore DESC, dog_clinic.visited DESC,我已经将它集成到查询中。

答案 1 :(得分:0)

好的,让我们再进一步了......通过左连接,这意味着并非所有的狗诊所都有一些“得分”等级...如果是这样,那个值将为NULL并且可能导致它扼流圈。

SELECT
      dc.*, 
      COALESCE( s.avgscore, 0 ) FinalAvg
   FROM 
      dog_clinic dc
         LEFT JOIN ( SELECT dcs.input_id,
                            AVG(dcs.score) AS avgscore
                        FROM 
                           dog_clinic_score dcs
                        GROUP BY 
                           dcs.input_id) s 
            ON dc.id = s.input_id
   ORDER BY 
      COALESCE( s.avgscore, 0 ) DESC,
      dc.visited DESC 
   LIMIT 
      0,10;