我正在为我正在为一个大学项目制作的框架构建一个 SQL 库。我已经完成了所有的辅助方法,但我对一件事感到困惑。
如何在 Have 子句中绑定参数或值,其中左侧参数是聚合函数,右侧参数是变量?
我创建了辅助方法,它们采用关联数组并将它们格式化为准备好的语句,所以我所要做的就是执行,
请看下面的最后一个例子,当左侧参数是聚合函数而右侧是变量时,如何设置参数以按值/参数绑定?
另外作为一个附带问题,是否可以在同一个 stmt 中同时拥有 bindparam 和绑定值?
任何建议都会有所帮助,如果有更好的方法,请告诉我,我知道我总是可以改变它,但我更喜欢这个选项
public function test_having()
{
$query = new Query();
$query
->select('name','age','height')
->from('Person')
->where('id','=',33)
->having('name','>',9867);
//Works perfectly
$this->assertEqualsIgnoringCase(
"SELECT name,age,height FROM Person WHERE id = :id HAVING name > :name ",
$query->get_query()
);
}
public function test_having_with_left_hand_side_aggregage_function($value='')
{
$query = new Query();
$height = 220;
$query
->select('max(age) as max_age','person')
->from('Person')
->where('age','>',50)
->group_by('max_age, person')
->having('max(height)','>',$height);
$this->assertEqualsIgnoringCase(
"SELECT max(age) as max_age,person
FROM Person WHERE age > :age GROUP BY max_age,person
//Not sure if this is a valid prepared stmt?:
HAVING count(reviews) > :count(reviews) ",
$query->get_query()
);
}
我有一个辅助方法,它循环遍历数组并将键、值和操作数传递给将这些添加到数组的方法,现在参数已正确设置,我只是不确定如何将变量绑定到聚合方法?
protected static function set_stmt($key, $op, $value, $logic_ops='')
{
if (is_object($value) && $value instanceof Query) {
$subquery = self::sort_subquery($value);
$stmt = $subquery['query'];
$stmt = ($logic_ops != '') ?
"$key $op $stmt $logic_ops " :
"$key $op $stmt ";
$result = [
'stmt' => $stmt,
'exec' => $subquery['exec'],
'params' => $subquery['params']
];
}else{
$params[$key] = ['key' => ":$key", 'value' => $value];
$stmt = ($logic_ops != '') ?
"$key $op :$key $logic_ops " :
"$key $op :$key ";
$result = [
'stmt' => $stmt,
'params' => $params,
];
}
return $result;
}