如何在Laravel Eloquent中使用MIN和MAX SQL查询

时间:2019-04-05 09:50:37

标签: mysql sql laravel laravel-5 eloquent

我想在同一行使用minmax laravel,这可行吗?

Appointmentsetting::where('Day','=',1)
->whereIn('PersonID', function ($query) {
    $query->select('p.id')
        ->from('users as p')
        ->join('appointmentsettings as aps', 'aps.PersonID', '=', 'p.id')
        ->where('p.active', '=', 1)
        ->where('aps.CompanyID', '=', 1)
        ->orWhereIn('aps.PersonID', function ($query2) {
            $query2->select('cps.user_id')
                    ->from('companypersonstructs as cps')
                    ->where('cps.CompanyID', '=', 1);
        })
        ->groupBy('aps.PersonID');
})
->where('active', '=', 1)
->select(\DB::raw("SELECT MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo"));
->get();

我出错了

  

SQLSTATE [42000]:语法错误或访问冲突:1064您有一个   您的SQL语法错误;检查与您的手册相对应的手册   MariaDB服务器版本可在'SELECT'附近使用正确的语法   MIN(StartFrom)AS StartFrom,MAX(EndTo)AS EndTo来自   第1行的“ appointmentsetting”

2 个答案:

答案 0 :(得分:3)

Appointmentsetting::where('Day','=',1)
->whereIn('PersonID', function ($query) {
    $query->select('p.id')
        ->from('users as p')
        ->join('appointmentsettings as aps', 'aps.PersonID', '=', 'p.id')
        ->where('p.active', '=', 1)
        ->where('aps.CompanyID', '=', 1)
        ->orWhereIn('aps.PersonID', function ($query2) {
            $query2->select('cps.user_id')
                    ->from('companypersonstructs as cps')
                    ->where('cps.CompanyID', '=', 1);
        })
        ->groupBy('aps.PersonID');
})
->where('active', '=', 1)
->select(\DB::raw("MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo"));
->get();

答案 1 :(得分:3)

->selectRaw(" MIN(StartFrom) AS StartFrom, MAX(EndTo) AS EndTo");

请在上面的查询中进行尝试。查询中的主要问题是您正在使用select两次,而在select或selectRaw中不需要写select 有关原始查询的更多信息,请单击here