【问题标题】:Laravel subqueryLaravel 子查询
【发布时间】:2016-04-07 05:52:38
【问题描述】:

我想在 laravel 5.2 中编写这个查询

SELECT b.id,
       TotalP,
       b.booking_amount
FROM booking b
LEFT JOIN
  (SELECT sum(amount) AS TotalP,
          booking_id
   FROM payment
   GROUP BY booking_id) AS T ON b.id = T.booking_id
WHERE COALESCE(TotalP, 0) < b.booking_amount

我的问题与这篇文章有关。 我在搜索和研究后写了一个查询,但它不起作用,需要更多约束

 $result = DB::table('my_booking')
        ->select('booking_name')
        ->leftJoin(DB::raw('(SELECT booking_id,sum(amount) as TotalP FROM `my_payment` GROUP BY booking_id) TotalPayment'), function($join)
        {
            $join->on('my_booking.id', '=', 'TotalPayment.booking_id');
        })
        ->get(); 

Sql query to get data diffrence of total in 2 tables

【问题讨论】:

    标签: php mysql database laravel


    【解决方案1】:

    你可以试试这个,

    $booking_payments = Booking::with('Payment')->find(1);
    
    $total = 0;
    foreach($booking_payments->payment as $booking_payment){
    $total += $booking_payment->amount;
    }
    
    if($booking_payments->booking_amount == $total){
    // if the total and booking_amount is equal
    }
    

    【讨论】:

      【解决方案2】:

      这应该可以在 Laravel 中运行,并为您提供与 MySQL 查询相同的结果。我将 COALESCE 移到子查询选择区域中,这样您就不必在 Laravel 中编写原始 DB where 语句。

      $sql_subquery = "(SELECT COALESCE(SUM(amount),0) AS TotalP,
                                booking_id
                         FROM payment
                         GROUP BY booking_id) AS T";
      
      
      $result = DB::table('booking AS b')
                  ->leftJoin(DB::raw($sql_subquery), 'b.id', '=', 'T.booking_id')
                  ->where('T.TotalP','<', 'b.booking_amount')
                  ->select('b.id','T.TotalP','b.booking_amount')
                  ->get();
      

      【讨论】:

        猜你喜欢
        • 2015-07-06
        • 2019-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 2021-11-09
        相关资源
        最近更新 更多