Laravel内部联接两个查询

时间:2014-09-27 09:53:26

标签: php mysql laravel laravel-4

我有一个查询,我正在加入两个查询以获得我想要的内容,我可以在SQL中管理这个问题但是我现在完全不知道我是怎么写的这对于Laravel来说。这是SQL:

select *
from 
    (
        select stu.s_nid as student_nid, stu.name as student_name, vote.id as vote_id
        from student stu
        left join vote on vote.student_id = stu.id
        where vote.vote_no != 0
    ) as q1
    inner join 
    (
        select stu.s_nid as nominee_nid, stu.name as nominee_name, vnd.nominee_type_id, vnd.vote_id, nt.name_ar
        from vote_nominee_details vnd
        left join nominee nom
        on nom.id = vnd.nominee_id
        left join student stu
        on stu.id = nom.student_id
        left join vote
        on vote.id = vnd.vote_id
        left join nominee_type nt
            on nt.id = vnd.nominee_type_id
        where vnd.vote_id is not null
        and vote.vote_no != 0
    ) as q2 on q1.vote_id = q2.vote_id

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

试试这个

$result = DB::select($sql);

你也可以试试这个

DB::table(DB::raw('(select stu.s_nid as student_nid, stu.name as student_name, vote.id as vote_id
        from student stu left join vote on vote.student_id = stu.id
        where vote.vote_no != 0) as q1'))
->join(DB::raw('(select stu.s_nid as nominee_nid, stu.name as nominee_name, vnd.nominee_type_id, vnd.vote_id, nt.name_ar from vote_nominee_details vnd 
        left join nominee nom on nom.id = vnd.nominee_id
        left join student stu on stu.id = nom.student_id
        left join vote on vote.id = vnd.vote_id
        left join nominee_type nt on nt.id = vnd.nominee_type_id
        where vnd.vote_id is not null and vote.vote_no != 0) as q2'), 'q2.vote_id', '=', 'q1.vote_id')
->get();