我怎么能压缩3个mysql查询;使用AVG和COUNT

时间:2014-03-31 21:28:53

标签: mysql join pdo

这些查询可以压缩成2个甚至更好的1个查询吗?

查询1

$stmt = $conn->
prepare("
    SELECT providers.Provider_ID, providers.Description, reviews.Date, reviews.F_Name, reviews.S_Name, reviews.Website, reviews.Rating, reviews.Message, reviews.Email_Address
    FROM providers
    INNER JOIN reviews ON reviews.Provider=providers.Provider_ID    
    WHERE providers.Provider_ID LIKE CONCAT('%',:provider,'%') LIMIT $set_limit 
");
$stmt->bindParam(':provider', $provider, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

查询2

$stmt = $conn->
prepare("
    SELECT ROUND(AVG(rating),1) as AVG_Rating
    FROM reviews
    WHERE Provider LIKE CONCAT('%',:provider,'%') 
");
$stmt->bindParam(':provider', $provider, PDO::PARAM_STR);
$stmt->execute();
$get_average = $stmt->fetchColumn();    

查询3

$stmt = $conn->
prepare("
    SELECT COUNT(*)
    FROM reviews
    WHERE Provider LIKE CONCAT('%',:provider,'%') 
");
$stmt->bindParam(':provider', $provider, PDO::PARAM_STR);
$stmt->execute();
$total_rows = $stmt->fetchColumn();

2 个答案:

答案 0 :(得分:1)

您将不同粒度级别的结果汇集在一起​​。一个是提供者级别,另一个是审阅级别。因此,您希望使用摘要信息进行评论。您可以通过加入汇总结果来获得此结果:

SELECT p.Provider_ID, p.Description, r.Date, r.F_Name, r.S_Name,
       r.Website, r.Rating, r.Message, r.Email_Address,
       tsum.AVG_Rating, tsum.cnt
FROM providers p INNER JOIN
     reviews r
     ON r.Provider = p.Provider_ID CROSS JOIN
     (SELECT Provider, ROUND(AVG(rating),1) as AVG_Rating, COUNT(*) as cnt
      FROM reviews
      WHERE Provider LIKE CONCAT('%',:provider,'%')
     ) tsum
WHERE p.Provider_ID LIKE CONCAT('%',:provider,'%')
LIMIT $set_limit

答案 1 :(得分:1)

查询2和查询3可以轻松组合成一个查询:

SELECT ROUND(AVG(rating),1) as AVG_Rating
     , COUNT(*) AS count_
FROM reviews
WHERE Provider LIKE CONCAT('%',:provider,'%')

但是您将无法使用fetchColumn(),您需要获取行并访问每一列。

此查询(如查询2和查询3)返回单行。查询1有可能返回0,1行或更多行,因此组合该查询会有一些问题。可以在每一行返回AVG_Ratingcount_,但处理该结果集的代码会稍微简单一些。