Error with leftJoin and select with where and sum
Hello,
I have some problem with my query where I can receive sum from column gross selling price from joined table with where clause. Im my localhost project this query work well but in remote server I have some problem with MardiaDB version.
This is error:
"message": "SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where doc_date BETWEEN ? AND ?)) as sale_amount from `order_products` left jo...' at line 1 (SQL: select order_products.shop_id as shop_id, count(status) as sold_count, ROUND(((count(status) * 100) / (select count(*) from order_products where status = sold)), 1) as sold_percent, SUM((select documents.gross_selling_price where doc_date BETWEEN 2022-05-10 AND 2022-05-11)) as sale_amount from `order_products` left join `documents` on `documents`.`id` = `sales_document_id` where `status` = sold and exists (select * from `orders` where `order_products`.`order_id` = `orders`.`id` and `orderable_type` = Shops) and `order_date` between 2022-05-10 and 2022-05-11 group by `shop_id` order by `sale_amount` desc)",
And this is piece of my query where in sum with select by date I have error:
$collection = OrderProduct::query()
->leftJoin('documents', 'documents.id', '=', 'sales_document_id')
->where('status', OrderProductStatusSold::$name)
->whereHas('order', function (Builder $query) use ($domain) {
$query->where('orderable_type', '=', $domain);
})
->selectRaw('order_products.shop_id as shop_id')
->selectRaw('count(status) as sold_count')
->selectRaw('ROUND(((count(status) * 100) / (select count(*) from order_products where status = ?)), 1) as sold_percent', [
OrderProductStatusSold::$name,
])
->when($date, function ($query) use ($date) {
if ($date) {
$query
->whereBetween('order_date', [$date[0], $date[1]])
->selectRaw('SUM((select gross_selling_price where doc_date BETWEEN ? AND ?)) as sale_amount', [
$date[0], $date[1]
]);
}
});
Im trying to designate a table like this but also get the same error as above:
->selectRaw('SUM((select documents.gross_selling_price where documents.doc_date BETWEEN ? AND ?)) as sale_amount', [
$date[0], $date[1]
]);
In my localhost project of course it works but not in remote server. Any ideas how I can make this select with date and sum?
Of course I know, I can make some relation to documents table but this is not optimal solution for me because documents table have 10 million records but I'm open to suggestion of course
Please or to participate in this conversation.