[英]laravel join with only limiting 2 row
所以我有这种查询,我像这样用最大日期/时间段进行分组
$table_data = App\salesreport::join(DB::RAW('(SELECT company_id, MAX(period) AS max_period FROM salesreport 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');
})->get()
它工作得很好,它可以将所有公司归为一个,然后只显示最新的一个MAX(period)
。 然后我想对其进行更多调整,如果我不仅要展示最新的,还要展示每家公司的最新两个怎么样? 所以每家公司将返回所有报告中最新的 2 份报告。
然后我想也许添加LIMIT 2
会使它起作用所以我这样说
$table_data = App\salesreport::join(DB::RAW('(SELECT company_id, MAX(period) AS max_period FROM salesreport 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');
$join->limit(2)
})->get()
但它没有效果,只显示所有周期 <= max_periods 的公司的所有报告。
为了让事情更清楚这里是我加入的表
这是我的销售报告表
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 1 | A1 | 500 | 2016-07-12 |
| 2 | A2 | 540 | 2017-01-21 |
| 3 | A1 | 440 | 2017-01-19 |
| 4 | A1 | 440 | 2018-01-19 |
| 5 | A2 | 330 | 2016-01-12 |
| 6 | A2 | 333 | 2018-01-22 |
+----+------------+-------+------------+
然后在那里使用第一个查询然后我会得到这种表
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 4 | A1 | 440 | 2018-01-19 |
| 6 | A2 | 333 | 2018-01-22 |
+----+------------+-------+------------+
所以我想要的是得到这种桌子
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 4 | A1 | 440 | 2018-01-19 |
| 3 | A1 | 440 | 2017-01-19 |
| 6 | A2 | 333 | 2018-01-22 |
| 2 | A2 | 540 | 2017-01-21 |
+----+------------+-------+------------+
所以每家公司的最新 2 个.. 有可能吗? 只有一个请求?
使用这个技巧:
App\salesreport::join(DB::RAW('(SELECT company_id, GROUP_CONCAT(periods ORDER BY periods DESC) grouped_periods FROM salesreport GROUP BY company_id ) latest_report'),function($join){
$join->on('salesreport.company_id','=','latest_report.company_id');
$join->whereBetween(DB::raw('FIND_IN_SET(`salesreport`.`periods`, `latest_report`.`grouped_periods`)'), [1, 2]);
})->get();
使用这个技巧:
App\salesreport::join(DB::RAW('(SELECT company_id, GROUP_CONCAT(periods ORDER BY periods DESC) grouped_periods FROM salesreport GROUP BY company_id ) latest_report'),function($join){
$join->on('salesreport.company_id','=','latest_report.company_id');
$join->whereBetween(DB::raw('FIND_IN_SET(`salesreport`.`periods`, `latest_report`.`grouped_periods`)'), [1, 2]);
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.