选择语句到另一个选择To Eloquant

时间:2015-12-01 09:01:11

标签: mysql sql eloquent

如何将这样的SQL查询转换为Eloquent或QueryBuilder:

SELECT * FROM studies
where studies.id in(SELECT study_id FROM (
SELECT max(studies.end_date), studies.id as study_id
from  workers inner join resumes on workers.id=resumes.worker_id
inner join studies on resumes.id=studies.resume_id where
resumes.title="main" group by workers.id) as SQ2

或全球

如何使用eloquant为其他select语句选择例如:

SELECT a.id from (SELECT * FROM A INNER JOIN B ON a.id=b.id where a.id > 10) as SUBQ1

1 个答案:

答案 0 :(得分:0)

我认为你当前的查询在所有情况下都没有得到带有max end_date的study_id,你可以试试这个:

SELECT * FROM studies
where studies.end_date in (
SELECT max(studies.end_date)
from  workers inner join resumes on workers.id=resumes.worker_id
inner join studies on resumes.id=studies.resume_id where
resumes.title="main" group by workers.id) 

如果你想使用laravel Eloquant实现,你可以这样做:

$result = DB::table('studies')
    ->select("*")
    ->whereIn('end_date', function($query){
    $query->selectRaw("max(studies.end_date) as max_date")
    ->from('workers')
    ->join('resumes', 'workers.id', '=', 'resumes.worker_id')
    ->join('studies', 'resumes.id', '=', 'studies.resume_id')
    ->where('resumes.title', '=', 'main')
    ->groupBy('workers.id');
    })
    ->get();
foreach($result as $row) {
        print_r($row);
    }