I have two MySQL tables, products, and barcodes. A product may have multiple barcodes, which is why I've separated it off into it's own table.
This is what I've tried (using CodeIgnighter's Active Record, but I've written out the query here, meaning if there is a typo, it might not be in my actual query):
SELECT products.id, products.snipe_price, group_concat(barcodes.barcode) as barcodes FROM products LEFT JOIN barcodes on barcodes.product_id = products.id
But this just returns one row with all of the barcodes from every product concat
ed, how can I get one row for each product with the products barcodes?
I'd rather not have to split it up, but if there is no solution with join
then please let me know.
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value.
The FULL JOIN keyword creates the result by combining the result of both a LEFT JOIN and a RIGHT JOIN . For any rows that aren't matching, the result will contain null values. This keyword is rarely used, but can be used to find duplicates, missing rows, or similar rows between two tables.
You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.
LEFT JOINs can return multiple matches on a single key value, depending on your requirements this may or may not be desirable. In Oracle, you can use the analytical function ROW_NUMBER to choose a single value when multiple matches on a key occur.
You need a group by
:
SELECT products.id, products.snipe_price, group_concat(barcodes.barcode) as barcodes FROM products LEFT JOIN barcodes on barcodes.product_id = products.id group by products.id;
Without the group by
, MySQL interprets the whole query as an aggregation query to summarize all the data (because of the presence of group_concat()
, an aggregation function). Hence it returns only one row, summarized on all the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With