如何使用Laravel Query Builder从Union结果中获取Min或Max值?

时间:2018-04-09 19:13:22

标签: laravel-5

我想从union表中获取最小值。

如下面的MySQL查询。

SELECT MIN(PromisedDate) 
FROM (SELECT PromisedDate FROM JobWorkOrder WHERE `PromisedDate` IS NOT NULL
    UNION
    SELECT ScheduledDate AS PromisedDate FROM JobPhase WHERE `ScheduledDate` IS NOT NULL) ScheduledTable;

此查询的结果是JobWorkOrder和JobPhase表中PromisedDate和ScheduledDate的最小值。

所以我构建了一个如下的Laravel查询。

$JobPhase = JobPhase::where('ScheduledDate', '<>', null)
    ->select('ScheduledDate AS PromisedDate');

$minDate = JobWorkOrder::where('PromisedDate', '<>', null)
    ->select('PromisedDate')
    ->union($JobPhase)
    ->min('PromisedDate');

但是我得到了错误的结果。 结果是

(SELECT MIN(`PromisedDate`) FROM `JobWorkOrder` WHERE `PromisedDate` IS NOT NULL) 
union 
(SELECT `ScheduledDate` AS `PromisedDate` FROM `JobPhase` WHERE `ScheduledDate` IS NOT NULL)

如何构建Laravel查询?

2 个答案:

答案 0 :(得分:2)

从子查询中选择min字段:

$JobPhase = JobPhase::where('ScheduledDate', '<>', null)
    ->select('ScheduledDate AS PromisedDate');

$sub = $JobWorkOrder = JobWorkOrder::where('PromisedDate', '<>', null)
    ->select('PromisedDate')
    ->union($JobPhase);

$minDate = DB::table( DB::raw("({$sub->toSql()}) as sub") )
    ->mergeBindings($sub->getQuery())
    ->min('PromisedDate');

另请参阅:How to select from subquery using Laravel Query Builder?

答案 1 :(得分:1)

你可以从get()函数结果得到min。 只需在查询中添加一个get()函数。

$JobPhase = JobPhase::where('ScheduledDate', '<>', null)
    ->select('ScheduledDate AS PromisedDate');

$minDate = JobWorkOrder::where('PromisedDate', '<>', null)
    ->select('PromisedDate')
    ->union($JobPhase)
    ->get()
    ->min('PromisedDate');

然后你会得到一个MIN值。