I have a query on the db of a shopping cart that involves a few outer joins that returns something like this (heavily simplified):
Orderid | Customer Name | Product | Image
1 | John | Prod1 | x.jpg
1 | John | Prod2 | e.jpg
2 | Paul | Prod3 | r.jpg
3 | Ringo | Prod1 | x.jpg
I would like the results to come out something like this
Orderid | Customer Name | Product1 | Image1 | Product2 | Image 2
1 | John | Prod1 | x.jpg | Prod2 | e.jpg
2 | Paul | Prod3 | r.jpg | NULL | NULL
3 | Ringo | Prod1 | x.jpg | NULL | NULL
Is this possible?
My previous query used a GROUP_CONCAT and had the result as a blob but I didn’t find it useful to work with.
To reliably get all of the products into a varying number of columns, you would need to use a
PIVOTfeature as present in DBMSs like SQL Server, Oracle, etc.In the case of MySQL, that sort of feature is not available and the best way to generate a CSV straight from the query (as you mentioned in the comments to your question) would be to use
GROUP_CONCAT().The reason why you had “blob” data in your
GROUP_CONCAT()before was because you were trying to concatenate two different data types into the string, and thus the phpMyAdmin was automatically converting it to[BLOB]. You must have been concatenating various integer values(ID’s, prices, etc.) along with string values. What you must do isCAST()the integer values to strings within yourGROUP_CONCAT()so that PMA doesn’t convert to blob. More info on CAST().Depending on what version of PMA you have, it may or may not convert to
[BLOB]. If it does, you could always expand+optionsand check “Show blob contents” and it will show the expected result.Just based on your above example (in addition to
product_idto illustrateCAST(), you could do something like:This would give you a result set along the lines of:
Then depending on the language you’re using to build your application, you can “explode” the
order_productsstring into arrays. First explode on the delimiter:::to separate products, then for each product, explode again on the delimiter|||to separate that product’s details.I use those particular delimiters because commas can be present in fields like the title, etc. and you would not want your script to separate the string in the wrong places. This possibility of erroneous separation is one of the major downsides to using
GROUP_CONCAT(), so you must decide which delimiters would be best to use based on the unlikelihood that they would be present within the field values.Also, watch out for nullable fields when using
CONCAT. For example, say for each product that theimagefield wasn’t required and could containNULL. If one part ofCONCAT()isNULL, then the entire concatted string will becomeNULL.So for whichever field is nullable, you would want to use
COALESCE()on the field to preventNULLs being passed toCONCAT(). (e.g.CONCAT(product, '|||', COALESCE(image, 'NoImage'))