E
E
elailasou2015-11-13 14:27:33
MySQL
elailasou, 2015-11-13 14:27:33

How to make a selection from tables on a many-to-many relationship and make a CONCAT in MySQL?

Probably already an annoying question for everyone, but still. Unfortunately, there is not enough time to study books on SQL yet, but you need to write a query.
There are 3 tables:
products

| id | name    |
|----|---------|
| 1  | Товар 1 |
| 2  | Товар 2 |

sizes
| id | value |
|----|-------|
| 1  | x     |
| 2  | xs    |
| 3  | m     |

And a linking table products_sizes with related id's of previous tables
| product_id | size_id |
|------------|---------|
| 1          | 1       |
| 1          | 2       |
| 2          | 2       |

How to make a selection and concatenation here, so that in the end we get a table like this:
| id | name    | sizes |
|----|---------|-------|
| 1  | Товар 1 | x;xs  |
| 2  | Товар 2 | m     |

Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat, 2015-11-13
@junk1114

Something like this (I am writing from the left computer, where there is no mysql - if anything, edit a little)

select product_id as id, products.name,
  group_concat(sizes.value separator ';') as sizes 
from product_sizes, sizes, products 
where product_id=products.id and size_id=sizes.id 
group by product_id

Added after the topic author's comment:
If it is necessary to display those products that do not have a size specified, then:
select products.id, products.name, 
  group_concat(sizes.value separator ';') as sizes 
from product_sizes 
  inner join sizes on (size_id=sizes.id) 
  right join products on (product_id=products.id) 
group by product_id order by id;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question