gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:10:49 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com