问题
I have 2 mysql tables:
car_model:
id (int) (Primary Key)
title (varchar)
id_brand (int) FK to car_brand table
car__car_model: - relation many to many
id_model (int)
id_advice_model (int)
In car__car_model there are the following data:
(id_model) (id_advice_model)
12 12
12 45
12 67
12 78
13 13
13 12
13 67
13 105
And I want to fetch this data like this:
12 12,45,67,78
13 13.12.67,105
I use group_concat and group by like this:
SELECT ccm.id_model,group_concat(ccm.id_advice_model) FROM car__car_model as ccm group by ccm.id_model
Question: How can fetch titles from car_model table for this string if ids - for example for 12,45,67,78. And I want to do it in 1 query - to customize my query
Updated: And Now I have another question: I Have one more table:
car_brand:
id (int) (PK)
title (varchar)
and in my car_model table there is a field id_brand
Question 2: How can i fetch title form car_brand with the title from car_model - like this - Ford Focus, Fiat Linea and so on - Now I get (with you help) to fetch only title from car_model Now I have: 12 - Focus,Linea
Updated: I solve this problem using -
SELECT
id_model,group_concat(concat(cb.title,' ',cm.title))
FROM
car__car_model as ccm
inner join car_model cm on (cm.id = ccm.id_advice_model)
inner join car_brand cb on (cb.id=cm.id_brand)
group by ccm.id_model
回答1:
Try this::
SELECT
ccm.id_model,group_concat(cm.tile, SEPARATOR ',')
FROM
car__car_model as ccm
inner join car_model cm on (cm.id = ccm.id_advice_model)
group by ccm.id_model
回答2:
SELECT ccm.id_model,
group_concat(cm.title)
FROM car__car_model as ccm
inner join car_model cm on cm.id = ccm.id_advice_model
group by ccm.id_model
You can replace the ids with the actual title by joining the car_model
table on the ids you like to replace.
来源:https://stackoverflow.com/questions/19311679/sql-group-concat-and-subquery