Laravel子查询与位置连接



所以我正在创建这种查询

$data = AppSalesReport::with('company')->join(DB::RAW('(SELECT company_id, MAX(periods) AS max_periods FROM laporancu GROUP BY company_id) latest_report'),function($join){
$join->on('salesreport.company_id','=','latest_report.company_id');
$join->on('salesreport.periods','=','latest_report.max_periods');
})->FilterPaginateOrder();

我想放where('periods','<=','2016-01-01')但我不知道应该放在哪里......

我试图把它放在with('company')之后,它不会返回 2015 年的销售报告,甚至认为我在数据库中有一些。所以在实验之后,我想我知道为什么会发生这种情况。

因为我有$join->on('salesreport.periods','=','latest_report.max_periods');,甚至认为salesreport.periods周期小于等于 2016-01-01,但正因为如此加入,它将始终匹配 latest_report

所以我认为我应该在查询执行时添加那些 where 子句

DB::RAW('(SELECT company_id, MAX(periods) AS max_periods FROM laporancu GROUP BY company_id) latest_report')

但是怎么做呢?我应该把它放在哪里?

更新:确切的SQL语句(无公司关系)

SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport GROUP BY company_id) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods
WHERE salesreport.periods <= 2016-01-01;

更新 2

所以我认为在检查了我的查询后,我发现我的查询有问题,所以在我的连接中,我确实MAX(periods),因此它将始终返回这些字段的最高值,问题是我想限制我想返回的值有多高。

所以也许有人可以想出其他办法来帮助我实现这一目标?

我在自己的代码中做了一些研究,因为我经常需要这个,想出了这个解决方案:

$data = AppSalesReport::with('company')->join(DB::RAW('(SELECT company_id, MAX(periods) AS max_periods FROM laporancu GROUP BY company_id) latest_report'),function($join){
$join->on('salesreport.company_id','=','latest_report.company_id');
$join->on('salesreport.periods','=','latest_report.max_periods');
})->where('periods','<=','2016-01-01')->FilterPaginateOrder();

如果这有效,请告诉我。如果没有,您得到什么错误:)

在搜索并四处寻求帮助之后,我终于得到了一个解决方案,它就像我需要的那样工作,所以这里是:

$periods = '2016-01-01';
$data = AppSalesReport::with('company')->join(DB::RAW('(SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods <= '$periods' GROUP BY company_id) latest_report'),function($join){
$join->on('salesreport.company_id','=','latest_report.company_id');
$join->on('salesreport.periods','=','latest_report.max_periods');
})->where('periods','<=','2016-01-01')->FilterPaginateOrder();

希望它可以帮助将来像我一样想要进行类似查询的任何人

最新更新