如何使用laravel Eloquent Querybuilder使用子查询编写选择查询?

时间:2017-06-21 05:42:38

标签: sql laravel laravel-5 eloquent query-builder

我从查询中得到了结果。

我的简单SQL是:

 SELECT
    o2.driver_id,
    total_delieveries,
    DATE_FORMAT(o1.created_at ,'%Y-%m-%d') AS created_at
FROM
    (
        SELECT
            driver_id,
            created_at,
            COUNT(driver_id) AS total_delieveries
        FROM
            orders
        WHERE
            is_paid = 0
        AND order_status = 5
        AND created_at BETWEEN "'.$first_Day.'"
        AND "'.$last_Day.'"
        GROUP BY DATE_FORMAT(created_at ,'%Y-%m-%d'),driver_id
    )
 o1 INNER JOIN orders o2 ON o1.driver_id = o2.driver_id GROUP BY o1.created_at

在Laravel源代码中,我编写了查询:

$responseData =  DB::select(DB::raw('select t.driver_id,total_delieveries,DATE_FORMAT(q1.created_at,\'%Y-%m-%d\') as created_at from (  SELECT driver_id, created_at, COUNT( driver_id ) AS total_delieveries FROM orders WHERE is_paid=0 AND order_status = 5 AND created_at BETWEEN "'.$first_Day.'" AND "'.$last_Day.'" GROUP BY DATE_FORMAT(created_at,\'%Y-%m-%d\'),driver_id) q1 INNER JOIN orders t ON q1.driver_id = t.driver_id GROUP BY q1.created_at'));

我得到了我想要的结果,但我想以更好的方式写出来。

请告诉我编写此查询的正确方法。

1 个答案:

答案 0 :(得分:5)

同样show这个答案和你的变体:

$subQuery = \DB::table('orders')->selectRaw('driver_id, created_at, COUNT(driver_id) AS total_delieveries')
    ->where('is_paid', 0)
    ->where('order_status', '5')
    ->whereBetween('created_at', [$first_Day, $last_Day])
    ->groupBy(\DB::raw('DATE_FORMAT(created_at ,"%Y-%m-%d"),driver_id'));

$q = \DB::table(\DB::raw('('.$subQuery->toSql().') as o1'))
    ->selectRaw('o2.driver_id,total_delieveries,DATE_FORMAT(o1.created_at ,"%Y-%m-%d") AS created_at')
    ->join('orders as o2', 'o1.driver_id', '=', 'o2.driver_id')
    ->groupBy('o1.created_at')
    ->mergeBindings($subQuery)
    ->get();