With the select statement below I'm getting a nice view of all my orders. But what I'm trying to achieve is to get all the totals and the individual ordered products in one select statement. Maybe the ordered products can be placed in an Array? If this is possible, I also would like to know the way to print these individual products.
Can anyone please advise? Thanks in advance.
SELECT statement:
SELECT order.order_id, DATE_FORMAT(order.date_added,'%Y/%m/%d - %H:%i'),
COUNT(order_product.order_id),
SUM(order_product.quantity),
SUM(order_product.cost)
FROM order
LEFT JOIN order_product ON order.order_id = order_product.order_id
GROUP BY order_product.order_id ORDER BY date_added DESC
GROUP_CONCAT is probably the most suitable thing here. It will concatenate multiple values into one string column. For example:
SELECT order.order_id, DATE_FORMAT(order.date_added,'%Y/%m/%d - %H:%i'),
GROUP_CONCAT(order_product.name SEPARATOR ', ') AS Products,
COUNT(order_product.order_id) AS NumberOfLines,
SUM(order_product.quantity) AS TotalQuantity,
SUM(order_product.cost) AS TotalCost
FROM order
LEFT JOIN order_product USING(order_id)
GROUP BY order_product.order_id
ORDER BY date_added DESC
You could alternatively use a separator of a single comma (that's the default), and then use explode(',', $products)
in PHP to get an array of the product names.