计算平均值和左联接表

时间:2018-10-03 17:37:47

标签: php mysql pdo

我正在尝试将基于rating的{​​{1}}列的平均值与另一个表合并。

我创建了这段代码来计算postid的平均值,并且可以正常工作:

rating

但是,当我尝试加入时,它不起作用,如下所示:

SELECT post_rating.postid, 
       AVG(post_rating.rating) 
FROM post_rating 
GROUP BY post_rating.postid"

如何加入此代码,或者有更好的方法呢?谢谢!

我正在使用的整个代码:

$join = ' LEFT JOIN ('SELECT post_rating.postid, 
                      AVG(post_rating.rating) 
                      FROM post_rating 
                      GROUP BY post_rating.postid') AS post_rating 
            ON post_rating.postid=theList.id';

以下是我的表格的简化版本:

postid表

<?php

$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'root', 'root');
$select = 'SELECT theList.id, theList.name, post_rating.rating, post_rating.postid';
$from = ' FROM theList';
$where = ' WHERE TRUE';
$join = ' LEFT JOIN ('SELECT post_rating.postid, AVG(post_rating.rating) FROM post_rating GROUP BY post_rating.postid') AS post_rating ON post_rating.postid=theList.id';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("pub", $opts)){
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)){
$where .= " AND bar = 1";
}
if (in_array("restaurant", $opts)){
$where .= " AND restaurant = 1";
}
if (in_array("club", $opts)){
$where .= " AND club = 1";
}

$sql = $select . $from . $join . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>

列表表

id | postid | rating
--------------------
1  |    3   |    5
2  |    3   |    4
3  |    1   |    3

我要输出的基本上是:

id | name 
----------
1  | name1   
2  | name2   
3  | name3

2 个答案:

答案 0 :(得分:1)

现在,我在上一个问题注释中看到了您要告诉我的问题,由于某种原因,您已经结束了$join字符串,因此将不包含大多数查询

所以这行

$join = ' LEFT JOIN ('SELECT post_rating.postid, AVG(post_rating.rating) 
            FROM post_rating GROUP BY post_rating.postid') AS post_rating 
            ON post_rating.postid=theList.id';

(请参阅代码颜色显示错误)

所以修改为

$join = ' LEFT JOIN (SELECT post_rating.postid, AVG(post_rating.rating) 
            FROM post_rating GROUP BY post_rating.postid) AS post_rating 
            ON post_rating.postid=theList.id';

我可以建议您将EXCEPTION处理添加到PDO中,以便在出现错误时在浏览器上得到提示。在您的连接代码中完成

$pdo = new PDO(.......);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

答案 1 :(得分:1)

我认为您正在以不必要的复杂方式处理此查询。只需在表之间进行pip uninstall -y darkflow & cd path\to\darkflow-master & pip install -e . ,将flow视为最左边的表,然后在Left Join上的分组依据中计算Avg()

theList

您的PHP代码如下:

postid