This is my table definition:
CREATE TABLE orders_total (
orders_total_id int unsigned NOT NULL auto_increment,
orders_id int NOT NULL,
title varchar(255) NOT NULL,
text varchar(255) NOT NULL,
value decimal(15,4) NOT NULL,
class varchar(32) NOT NULL,
sort_order int NOT NULL,
PRIMARY KEY (orders_total_id),
KEY idx_orders_total_orders_id (orders_id)
);
A populated table can look something like this (all made-up numbers from my memory):
1 - 13 - Shipping - $7.50 - 7.50 - ot_shipping - 2
2 - 13 - Tax - $8.00 - 8.00 - ot_tax - 4
3 - 13 - Total - $56.67 - 56.67 - ot_total - 3
4 - 14 - Shipping - $5.55 - 5.55 - ot_shipping - 2
5 - 14 - Discount - $6.40 - 6.40 - ot_discount - 1
6 - 14 - Coupon - $10.00 - 10.00 - ot_coupon - 5
7 - 14 - Total - $150.25 - 150.25 - ot_total - 3
Every order can have different classes, and not all orders have to have the exact number of classes. For example:
- Order 1 can have the following classes: ot_shipping, ot_tax, ot_total
- Order 2 can have the following classes: ot_shipping, ot_discount, ot_coupon, ot_total
- …
I’d like to write a query that queries my orders table (not displayed here), and joins the above table (orders_total), and grabs the “value” column only if the “class” is either “ot_total”, “ot_coupon”, or “ot_discount”.
Here is my attempt at creating such a query:
SELECT o.orders_id, o.customers_name, group_concat(ot.value) AS values
FROM orders o
LEFT JOIN orders_total ot
ON ot.orders_id = o.orders.id
GROUP BY o.orders_id
The above query would produce something like this:
First set of results:
orders_id => 13
customers_name => John Doe
values => 7.50,8.00,56.67
Second set of results:
orders_id => 14
customers_name => Jane Roe
values => 5.55,6.40,10.00,150.25
As you can see, the values gives me what I need, but I just don’t know what number belongs to which class. I’m only interested in ot_total, ot_discount, and ot_coupon.
Anybody can think of any solution?
Is it possible to somehow append the class name to the values as well? So I can have something like values => ot_shippimh7.50,ot_tax8.00,ot_total56.67
You can do this:
BTW: You can do better, by remove the class field from your
orders_total, add a new table calledClassesinstead that contains a list of classes then add a foreign key reference to this table to yourorders_total.