【发布时间】:2020-05-27 01:34:49
【问题描述】:
我有两个变量 $customers(保存所有行)和 $total 保存查询的总行数。
我通常会做如下查询:
$customers = Customers::select
(
'customer.id',
'customer.name',
'customer.min_tolerance',
DB::raw('(SELECT MAX(tolerance) FROM customers_tolerances WHERE customer_id = customer.id) AS tolerance')
)
->from('customers AS customer')
->whereIn('customer.id', $request->customers);
$total = $customers->count();
$customers = $customers->limit($request->limit)
->offset($request->offset)
->get();
这很好用。我得到了所有行的限制(通常每页 20 行)加上总行数。
我的问题是我在查询中添加了having 子句,所以现在看起来像这样:
$customers = Customers::select
(
'customer.id',
'customer.name',
'customer.min_tolerance',
DB::raw('(SELECT MAX(tolerance) FROM customers_tolerances WHERE customer_id = customer.id) AS tolerance')
)
->from('customers AS customer')
->whereIn('customer.id', $request->customers)
->havingRaw('tolerance >= customer.min_tolerance');
而$count 因触发错误而停止工作:
未找到列:1054“有子句”中的“容差”列未知
select count(*) as aggregate from customers as customer having tolerance >= customer.min_tolerance)
那么我如何将count 与having 子句一起使用?
【问题讨论】:
-
如果您已经从“客户”模型中进行选择,我认为您不需要
->from('customers as customer')。另外,请检查此答案。 stackoverflow.com/questions/50081540/laravel-where-count-n -
你的having子句中必须有一个聚合函数。
-
having是不必要的,因为聚合位于子查询中。只需将其更改为 whereRaw -
@aynber 您无法使用
where访问别名变量。 -
@Hardood 你的意思是
SELECT COUNT(*) FROM (SELECT ...)。如果是这样,我的问题是,我已经尝试过,是查询速度很慢。