mysql - 缺少在 F3 中使用 SQL 的 HAVING 子句的选项

标签 mysql fat-free-framework

有没有办法将 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/

相关文章:

PHP/MySQL 连接 2 个表

mysql - "foreach"循环 : Using all cores in R (especially if we are sending sql queries inside foreach loop)

mysql - 在无脂框架中运行准备好的语句

php - 推荐简单的PHP路由引擎

php - fatfree SQL 错误处理

php - 使用 PHP foreach 循环创建 MySQL 表 - 语法错误

php - 如何检查我是否创建了最佳的mysql数据库?

php - session 数据未写入数据库

mysql - 如何使用fat-free ORM将数据插入到仅id表中?