2016-09-17 36 views
0

即时得到以下错误:雄辩质疑2个表

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'value' in 'where clause' (SQL: select sum(gross) as value, first_name from clients left join transactions on clients . id = transactions . client_id where value > 0 group by first_name)

从这个功能呢?

$data = DB::table('clients')->leftjoin('transactions','clients.id','=','transactions.client_id') 
     ->select(DB::raw('sum(gross) as value, first_name')) 
     ->where('value','>',0) 
     ->groupBy('first_name') 
     ->get(); 

return $data; 

回答

0

SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of sum(gross) to value has not yet occurred.

Aliases can be used in GROUP BY, ORDER BY, or HAVING clauses.

因此,而不是在请在下面一样使用sum(gross)使用value

$data = DB::table('clients')->leftjoin('transactions','clients.id','=','transactions.client_id') 
     ->select(DB::raw('sum(gross) as value, first_name')) 
     ->where('sum(gross)','>',0) 
     ->groupBy('first_name') 
     ->get(); 

return $data; 
+0

感谢拉胡尔,我看到如何可以工作由我收到以下错误: –

+1

SQLSTATE [42000]:语法错误或访问冲突:1463非分组字段“值”在HAVING子句(SQL使用: select'sum(gross)as value,first_name from'clients' left join'transactions' on'clients'.'id' ='transactions'.'client_id' group by'first_name' having'value'> 0) –

+0

请检查我的更新后。实际上,您可以直接在条件中使用总和(总数),而不是使用别名。对于有错的想法感到抱歉。只有你可以把条件放在分组字段上。 –