缺少在F3

时间:2016-09-30 13:14:52

标签: mysql fat-free-framework

有没有办法在任何Fat Free Framework's SQL Mapper object's方法中使用MySQL' HAVING子句?我们假设我有以下数据库表:

+----+-------+--------+
| 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

2 个答案:

答案 0 :(得分:1)

使用子查询。

select count (0) from (SELECT id, SUM(score*weight)/SUM(weight) AS weighted_score GROUP BY id) where weighted_score>2;

希望它会有所帮助。

答案 1 :(得分:1)

据我所知,您可以将HAVING子句放入组选项中:

$usersInfo = $dataMapper->find([],["group"=>"id HAVING weighted_score<2"]);

另一种方法是在mysql中创建一个VIEW并过滤该视图中虚拟字段的记录。