Mysql 如何从其他表中获取值以集成到子查询中?
我的表A如下:Mysql 如何从其他表中获取值以集成到子查询中?,mysql,laravel-5,join,subquery,Mysql,Laravel 5,Join,Subquery,我的表A如下: ID | NegeriID | yeartamatkhidmat | yeartamatkhidmat ----------------------------------------------------------------- 1 | 2 | 2001 | 2002 1 | 2 | 2003 | 2007 2 | 2 | 2008
ID | NegeriID | yeartamatkhidmat | yeartamatkhidmat
-----------------------------------------------------------------
1 | 2 | 2001 | 2002
1 | 2 | 2003 | 2007
2 | 2 | 2008 | 2012
2 | 1 | 2013 | 2018
3 | 3 | 2000 | 2001
$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(州),我有一个子查询来获得多年工作经验的总和,如下所示:
ID | NegeriID | yeartamatkhidmat | yeartamatkhidmat
-----------------------------------------------------------------
1 | 2 | 2001 | 2002
1 | 2 | 2003 | 2007
2 | 2 | 2008 | 2012
2 | 1 | 2013 | 2018
3 | 3 | 2000 | 2001
$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');
我有另一个值为name和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
答案是您加入到这些其他表中。但是,我无法大胆回答,因为您的查询/Laravel代码太复杂。是的,我尝试使用righ join进行连接,但出现错误“语法错误或访问冲突:1055'dbhre1m_v2_migrate.itemregistrations.ItemRegistrationID'不在GROUP BY中”我已经将查询简化为相关的问题。答案是您将加入这些其他表。但是,我不敢回答,因为您的查询/Laravel代码太复杂。是的,我尝试使用righ join加入,但出现错误“语法错误或访问冲突:1055'dbhre1m_v2; u migrate.itemregistrations.ItemRegistrationID'不在组中BY”我已将查询简化为相关问题。