作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有没有办法将 MySQL 的 HAVING 子句与 Fat Free Framework's SQL Mapper object's 中的任何一个一起使用方法?假设我有以下数据库表:
+----+-------+--------+
| id | score | weight |
+----+-------+--------+
| 2 | 1 | 1 |
| 2 | 2 | 3 |
| 2 | 3 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 4 |
| 3 | 3 | 1 |
| 3 | 4 | 3 |
+----+-------+--------+
现在我想运行以下查询:
SELECT id, SUM(score*weight)/SUM(weight) AS weighted_score GROUP BY id HAVING weighted_score>2
说实话,我实际上想计算这些记录的数量,但 count
方法不支持 $options
。
我可以在没有HAVING
子句的情况下运行查询,然后循环遍历它们以根据值检查weighted_score
,但是随着记录数量的增加,它会变得越来越多更消耗资源。有没有内置的解决方案可以解决这个问题?
编辑1:如果不支持 HAVING
子句(基于 manual ),我知道如何执行此操作:
$databaseObject = new DB\SQL(...);
$dataMapper = new \DB\SQL\Mapper($databaseObject, "tableName");
$dataMapper->weightedScore = "SUM(weight*score)/SUM(weight)";
$usersInfo = $dataMapper->find([],["group"=>"id"]);
$place = 1;
foreach ( $usersInfo as $userInfo ) {
if ( $usersScores->weightedScore > 2) $place++;
}
如果我能够使用 HAVING
子句,则不需要 foreach 循环,并且查询加载的项目数将会减少:
$databaseObject = new DB\SQL(...);
$dataMapper = new \DB\SQL\Mapper($databaseObject, "tableName");
$dataMapper->weightedScore = "SUM(weight*score)/SUM(weight)";
$usersInfo = $dataMapper->find([],["group"=>"id", "having"=>"weighted_score<2"]); // rough idea
$place = count($usersInfo);
如果 count
method支持 $options
它会更简单,并且会节省应用程序使用的内存,因为不会加载记录:
$databaseObject = new DB\SQL(...);
$dataMapper = new \DB\SQL\Mapper($databaseObject, "tableName");
$dataMapper->weightedScore = "SUM(weight*score)/SUM(weight)";
$place = $dataMapper->count([],["group"=>"id", "having"=>"weighted_score<2"]); // rough idea
最佳答案
使用子查询。
select count (0) from (SELECT id, SUM(score*weight)/SUM(weight) AS weighted_score GROUP BY id) where weighted_score>2;
希望对您有所帮助。
关于mysql - 缺少在 F3 中使用 SQL 的 HAVING 子句的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39792443/
我是一名优秀的程序员,十分优秀!