查询和子查询在laravel中加入

时间:2017-04-19 08:14:58

标签: php database postgresql laravel

我在laravel上尝试这个但是我得到这样的错误

SQLSTATE[42601]: Syntax error: 7 ERROR: subquery in FROM must have an alias
 LINE 3: (select * from subcategory a inner join s...
HINT: For example, FROM (SELECT ...) [AS] foo. (SQL: select * from 
mastercategory c
inner join 
 (select * from subcategory a inner join subling b on 
a.idsubcategory=b.idsubcategory_subcategory) on c.idcategory=a.idsubcategory_subcategory 

我试图加入mastercatergory和(subategory and subling)的连接子查询

   $users = DB::select(DB::raw(" select *  from mastercategory c
            inner join  (select * from subcategory a inner join subling b on 
            a.idsubcategory=b.idsubcategory_subcategory) on 
            c.idcategory=a.idsubcategory_subcategory "))->get();

我如何能够实现这一点我不想提前使用模型

这是我的更新

   $users  =   DB::raw(" select a.*,b.*  from mastercategory a
                  inner join  
               (select b.*,c.* from subcategory b inner join subling c  on  
           b.idsubcategory=c.idsubcategory_subcategory) on 
          a.idcategory=b.idcategory_mastercategory"); 

为什么我得到空值

2 个答案:

答案 0 :(得分:2)

 $users = DB::select("select *  from mastercategory c
            inner join  (select * from subcategory a inner join subling b on 
            a.idsubcategory=b.idsubcategory_subcategory) as d on 
            c.idcategory=d.idsubcategory_subcategory");

当您使用DB::select时,它会执行该语句并返回结果。您无需使用getDB::rawcheck here)。

您收到此错误是因为您没有提供内部子查询的别名。

答案 1 :(得分:2)

您必须为每个子查询命名。例如,使用此:

select * from mastercategory c
inner join 
  (select * from subcategory a 
   inner join subling b on a.idsubcategory=b.idsubcategory_subcategory) as sub 
on c.idcategory=sub.idsubcategory_subcategory

我已将粗体部分:a.idsubcategory = b.idsubcategory_subcategory)添加为 sub