2016-09-17 72 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

請檢查我的更新後。實際上,您可以直接在條件中使用總和(總數),而不是使用別名。對於有錯的想法感到抱歉。只有你可以把條件放在分組字段上。 –