Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL left join with multiple rows on right, how to combine to one row for each on left (with the field I want from the right table concated)?

Tags:

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 concated, 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.

like image 700
John V. Avatar asked Jul 16 '13 02:07

John V.


People also ask

Can I concatenate multiple MySQL rows into one field?

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.

How do I combine left and right JOINs?

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.

How do I combine multiple rows into one column in SQL?

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.

WHAT IF LEFT join has multiple matches?

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.


1 Answers

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.

like image 181
Gordon Linoff Avatar answered Sep 20 '22 15:09

Gordon Linoff