php - 计算平均和左连接表
问题描述
我正在尝试将rating
基于 的列的平均值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';
我该如何加入此代码,或者有更好的方法吗?谢谢!
我正在使用的整个代码:
<?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);
?>
这是我的表格的简化版本:
postid 表
id | postid | rating
--------------------
1 | 3 | 5
2 | 3 | 4
3 | 1 | 3
列表表
id | name
----------
1 | name1
2 | name2
3 | name3
我试图基本上输出的是:
id | name | rating
------------------
1 | name1 | 3
2 | name2 | 0
3 | name3 | 4.5
解决方案
现在我看到您在之前的问题评论中试图告诉我的问题,您$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';
我可以建议您向 PDO 添加异常处理,以便在出现错误时在浏览器上得到通知。在您的连接代码中执行此操作
$pdo = new PDO(.......);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
推荐阅读
- git - 如何 git init 特定文件或文件夹不包括同一目录中的所有其他文件或文件夹?
- apache-kafka - 在 SparkStreaming 中暂停和恢复 KafkaConsumer
- python - 评估测试脚本时出错:SyntaxError: Unexpected token ':'
- spring-boot - 此应用程序没有 /error 的显式映射,因此您将其视为后备..Whiteable 错误页面
- sockets - socket 究竟如何在较低级别接收工作(例如 socket.recv(1024))?
- oracle - EF Core 中不区分大小写的索引映射
- regex - 要匹配的正则表达式模式 - Javascript
- qt - QSqlRelationalModel:我调用setRelation(...)后,模型中的列似乎被外部表中的列替换了
- sql-server - 将 SQL bacpac 从 onprem 导入到 azure,错误 - 数据库中已经存在一个对象
- javascript - 在 mongodb 检查错误类型时我得到了未定义