![](/img/trans.png)
[英]MySQL get count of all rows in another table where the value equals column in current table
[英]Select all rows where the sum of column equals a value of another column on another table in Laravel
選擇列總和等於Laravel中另一個表上另一列的值的所有行
購買
id | name | amount
1 | Gamerzone Book | 40
2 | Recipe Book | 20
3 | EngineX Book | 10
付款方式
id | purchase_id | amount
1 1 25
2 1 15
2 2 10
碼
$query = DB::table('purchases')
->select(['purchases.id','purchases.name',
DB::raw("IFNULL(sum(payments.amount),0) as total")
])
->leftJoin('payments','payments.purchase_id','=','purchases.id')
->having('amount','=',DB::raw('total'));
->groupBy('purchases.id')->get();
當我運行代碼時,出現以下錯誤找不到列:1054“具有子句”中的未知列“金額”
預期結果
id | name | total
1 | Gamerzone Book 40
我嘗試了所有這些,但似乎沒有任何效果
$query->where('purchases.amount','=',DB::raw('total'));
$query->having(DB::raw('purchases.amount'),'=',DB::raw('total'));
$query->havingRaw('IFNULL(sum(purchases.amount),0) = purchases.amount');
$paymentsQuery = DB::table('payments')->select(DB::raw("IFNULL(sum(payments.amount),0) as total"))->whereRaw('purchases.id = purchase_id')->groupBy('purchase_id');
$purchasesQuery = DB::table('purchases')->select(['id', 'name', 'amount', DB::raw('(' . $paymentsQuery->toSql() . ') as total')])->havingRaw('amount = total')->mergeBindings($paymentsQuery);
$result = $purchasesQuery->get();
$ paymentsQuery將作為子查詢來獲取每個購買行的總計。
結果我們得到像這樣的sql:
select `id`, `name`, `amount`,
(select IFNULL(sum(payments.amount),0) as total from `payments` where purchases.id = purchase_id group by `purchase_id`) as total
from `purchases`
having amount = total
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.