Answer the question
In order to leave comments, you need to log in
How to make group by with saving some columns?
Hello!
There are two tables: Orders and OrderProducts.
I make a request to get the user's orders and the products in this order.
SELECT orders.num, orders.createdon, orders.cost, orders.status, products.name, products.count, products.cost
FROM `modx_ms2_orders` AS orders
JOIN `modx_ms2_order_products` AS products ON orders.id = products.order_id
WHERE `user_id` = 106
Answer the question
In order to leave comments, you need to log in
The simplest option is to use GROUP_CONCAT
SELECT
orders.num, orders.createdon, orders.cost, orders.status,
GROUP_CONCAT(products.name) prod_names,
GROUP_CONCAT(products.count) prod_counts,
GROUP_CONCAT(products.cost) prod_costs
FROM `modx_ms2_orders` AS orders
JOIN `modx_ms2_order_products` AS products ON orders.id = products.order_id
WHERE `user_id` = 106
GROUP BY orders.num, orders.createdon, orders.cost, orders.status
No. You will not be able to make a selection with an arbitrary number of fields.
The maximum that can be done here is to collapse these fields into JSON.
SELECT `o`.`num`, `o`.`createdon`, `o`.`cost`, `o`.`status`, `p`.`products`
FROM `modx_ms2_orders` AS `o`
LEFT JOIN (
SELECT `order_id`,
JSON_ARRAYAGG(
JSON_OBJECT('name', `name`, 'price', `price`, 'count', `count`)
) AS `products`
FROM `modx_ms2_order_products`
GROUP BY `order_id`
) AS `p` ON `p`.`order_id` = `o`.`id`
WHERE `o`.`user_id` = 106
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question