可以以某种方式优化此查询吗?

时间:2019-11-15 06:21:29

标签: mysql sql laravel

这是性能上很好的查询,还是我可以某种方式优化此查询?我需要从rental_schedules表中选择日期列,然后计算有多少可用的相同日期可用(rental_schedule_status = 1):

$reservationTimes = RentalSchedule::distinct()
        ->select('date',
        DB::raw('(SELECT count(date) FROM rental_schedules AS r2 
        WHERE r2.date = rental_schedules.date and rental_schedule_status = 1) as free_time'))
        ->where('premises_id', $id)->pluck('free_time', 'date');

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试使用左联接子查询来短语您的查询,例如

SELECT
    rs1.date,
    COALESCE(rs2.cnt, 0) AS free_time
FROM rental_schedules rs1
LEFT JOIN
(
    SELECT date, COUNT(*) AS cnt
    FROM rental_schedules
    WHERE rental_schedule_status = 1
    GROUP BY date
) rs2
    ON rs1.date = rs2.date
WHERE
    rs1.premises_id = ?;

您更新的Laravel代码:

$reservationTimes = RentalSchedule:from("RentalSchedule AS rs1")
    ->select(DB::raw('rs1.date, COALESCE(rs2.cnt, 0) AS free_time'))
    ->join(DB::raw('(SELECT date, COUNT(*) AS cnt
                     FROM rental_schedules
                     WHERE rental_schedules_status = 1
                     GROUP BY date) rs2'),
    function($join) {
        $join->on('rs1.date', '=', 'rs2.date');
     })
->where('premises_id', $id)
->pluck('free_time', 'date');

您也可以尝试在(rental_schedules_status, date)上添加索引,以加快子查询的速度:

CREATE INDEX idx ON rental_schedules (rental_schedules_status, date)

答案 1 :(得分:1)

无需连接或子查询即可获得结果:

尝试一下:

$reservationTimes = RentalSchedule::select('date',\DB::Raw("sum(case when rental_schedule_status = 1 then 1 else 0 end) as free_time"))
                ->where('premises_id', $id)
                ->groupBy('date')
                ->get()
                ->pluck('free_time', 'date');