A
A
apptimeru2015-09-29 22:14:38
MySQL
apptimeru, 2015-09-29 22:14:38

SQL string concatenation (one to many)?

Hello experts, please tell me I could not find information on how to make such a request.
There is one table, say, with goods, one with categories, and 3 tables that combine, i.e. it specifies the product ID and the ID of the corresponding category.
Let's say a product can belong to 2 categories at once, respectively, in the 3rd table we will have 2 records.
So how to display all products and next to their categories if each product can have several categories? Those. it turns out that when you query, you need to combine 1 row from one table with 2 or more other tables?
I tried in this way

SELECT base. * , meta.value
FROM  `base` 
LEFT OUTER JOIN meta ON meta.id = base.id

With such a request, it simply duplicates the line with the product and assigns one category to each, as a result, we have a lot of duplicate products.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Leonid Sysoletin, 2015-09-29
@apptimeru

There are three tables in the condition.

SELECT g.id, g.name, GROUP_CONCAT(m.name)
FROM goods AS g
    LEFT JOIN goods_meta AS gm ON (goods.id = gm.goods_id)
    LEFT JOIN meta AS m ON (m.id = gm.meta_id)
GROUP BY g.id

I
Ivanq, 2015-09-29
@Ivanq

As far as I remember it should work

SELECT base. * , meta.value
FROM  `base`, `meta`
WHERE meta.id = base.id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question