`GROUP_CONCAT()`多对多

时间:2016-01-11 11:56:53

标签: mysql sql join

我有3个表:typesbrandstype_brand

类型id|title|slug

品牌id|title|slug

type_brand id|type_id|brand_id

因此,我需要在结果列中获取brands表中带有types的所有记录。像这样:

id | title | slug | types
1     tit    TIT    type1,type2,type3

我为此写了查询:

select brand.title, brand.slug, GROUP_CONCAT(j2.slug) AS types
  from brand brand
LEFT join type_brand j1 on j1.brand_id = brand.id
LEFT join types j2 on j2.id = j1.type_id
limit 10

这是错误的,因为获得只有type_brand表中的品牌。 我需要在表brands中获得所有品牌,并在结果中添加可选列types

帮帮我

1 个答案:

答案 0 :(得分:3)

您只需要GROUP BY吗?

select brand.title, brand.slug, GROUP_CONCAT(j2.slug) AS types
from brand brand LEFT join
     type_brand j1
     on j1.brand_id = brand.id LEFT join
     types j2
     on j2.id = j1.type_id
group by brand.title, brand.slug 
limit 10;