如何从其他表中获取价值以整合到子查询中?

时间:2019-05-02 04:58:31

标签: mysql laravel-5 join subquery

我的表A如下:

 ID | NegeriID  | yeartamatkhidmat | yeartamatkhidmat
-----------------------------------------------------------------
 1  |     2     |      2001        |      2002
 1  |     2     |      2003        |      2007
 2  |     2     |      2008        |      2012
 2  |     1     |      2013        |      2018
 3  |     3     |      2000        |      2001

根据Negeri(州),我有一个子查询来获取多年工作经验的总和:

 $query = DB::table('B')
                ->select('B.name','B.ID', '');


 $query->select(DB::raw('B.name, m.NegeriID, sum(distinct m.duration)'))
                  ->from(DB::raw('(SELECT ID, NegeriID, yeartamatkhidmat - yearmulakhidmat as duration FROM A) AS m 
                    RIGHT JOIN B ON B.ID=m.ID'))
                  ->groupBy('m.ID', 'm.NegeriID');

我还有另一个表,其名称和值为Negeri:

表B

    ID |  Name 
    --------------
    1  |  Bill   
    2  |  Jane   
    3  |  Roy     

表C

   NegeriID |  Negeri 
    --------------
       1    |    E  
       2    |    F  
       3    |    G

如何从表中获取name和Negeri的值以集成到上面的子查询中?

我尝试过以下代码:

 $query->JOIN(DB::RAW('(SELECT m.itemRegistrationID, m.NegeriID, sum(distinct m.duration) AS s 
                                        FROM (SELECT itemRegistrationID, NegeriID, yeartamatkhidmat - yearmulakhidmat as duration FROM itemregistrationpangkat) AS m)'),
                                      function($join){
                                        $join->on("itemregistrations.itemRegistrationID","=","m.itemRegistrationID");
                                      })
                  ->groupBy('m.itemRegistrationID', 'm.NegeriID');

但显示错误:

    Syntax error or access violation: 1248 Every derived table must have its own alias 

0 个答案:

没有答案