I have three tables: store_products
, store_orders
and store_orders_products
. store_products
contains all of the products, store_orders
contains the order information, and store_orders_products
contains each individual product in that order.
I'm building an Orders page that will list each order placed. It will have the username of the person who placed the order, the date, the total amount and the name of each product.
This query gets me everything I want, except it returns only ONE product name. I want to have each product in a comma separated string. I've tried subqueries, COALESCE
, CONCAT
, IN()
, etc, but I'm not getting the results I want.
SELECT
o.id AS order_id
, o.order_total
, o.created_at
, u.username
, u.avatar
, sp.name
FROM store_orders o
JOIN store_orders_contents c ON o.id=c.oid
JOIN store_products p ON p.id=c.pid
JOIN users u ON u.id=o.consumer_uid
JOIN store_products sp ON sp.id=c.pid
WHERE p.uid=3
GROUP BY order_id
I think you want group_concat()
:
SELECT o.id AS order_id, o.order_total, o.created_at, u.username, u.avatar,
group_concat(sp.name )
FROM store_orders o JOIN
store_orders_contents c
ON o.id = c.oid JOIN
store_products p
ON p.id = c.pid JOIN
users u
ON u.id = o.consumer_uid JOIN
store_products sp
ON sp.id = c.pid
WHERE p.uid = 3
GROUP BY order_id;
I don't understand why you are joining to store_products
twice, but I assume you know what you are doing with the joins.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.