【问题标题】:How to join sub-query in laravel elequent如何在 laravel eloquent 中加入子查询
【发布时间】:2020-07-05 01:18:47
【问题描述】:

如何在 laravel 查询生成器中查询?

select * from products p join 

(
select product_id,sum(qty) total_sales 

from orders where qty !=0 group by product_id
) 

s on p.id = s.product_id

order by s.total_sales desc

【问题讨论】:

标签: mysql laravel eloquent


【解决方案1】:

有不同的方法来做同样的事情。但是你可以用Raw Expressions做的很像你上面的代码。

【讨论】:

  • 你的问题一到?
【解决方案2】:

如果您想使用 Eloquent,请执行此操作,前提是订单表的 product_id 是产品的外键

DB::table('products')->join('orders','products.id','orders.product_id')->where('orders.qty','!=',0)->get()

【讨论】:

    【解决方案3】:

    joined 部分的子查询的第一部分。它与raw 语句中的toSql() 方法结合在一起。

    $subQuery = DB::table('orders')
        ->where('qty', '!=', DB::raw(0))
        ->groupBy('product_id')
        ->select('product_id', DB::raw('sum(qty) as total_sales'));
    
    return DB::table('products as p')
        ->join(DB::raw('(' . $subQuery->toSql() . ') s'), 'p.id', '=', 's.product_id')
        ->orderByDesc('s.total_sales')
        ->get();
    

    它打印以下sql;

    SELECT *
    FROM `products` AS `p`
             INNER JOIN (
        SELECT `product_id`, SUM(qty) AS total_sales
        FROM `orders`
        WHERE `qty` != 0
        GROUP BY `product_id`
    ) s ON `p`.`id` = `s`.`product_id`
    ORDER BY `s`.`total_sales` DESC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多