我需要使用多个JOIN构建一个查询,更具体地说,2个JOINS,但它会得到重复的结果,请检查:
我目前的表格:
food_shops
id, slug, name
categories_food_shops
id, id_cat, id_food_shop
pictures_food_shops
id, pic_slug, id_food_shop
我需要从food_shops获得*,来自categories_food_shops的id_cat和来自pictures_food_shops的pic_slug ......
我目前的查询是这样的:
SELECT food_shops.id, food_shops.slug, food_shops.name,
GROUP_CONCAT(categories_food_shops.id_category) as categories,
GROUP_CONCAT(pictures_food_shops.slug) as pictures
FROM
food_shops
JOIN categories_food_shops
ON food_shops.id = categories_food_shops.id_food_shop
JOIN pictures_food_shops
ON food_shops.id = pictures_food_shops.id_food_shop
GROUP BY food_shops.slug, pictures_food_shops.id_food_shop
但由于我的pictures_food_shops作为categories_food_shops有更多的结果,我的结果是“四倍”:
我该怎么做才能防止这种情况并获得正确数量的类别? 第一行只有1,第二行只有3和5,最后一行是7,1,6?
谢谢!
答案 0 :(得分:0)
你可以试试这个:
...
GROUP_CONCAT(DISTINCT categories_food_shops.id_category) as categories,
....
这也适用于图片。
使用DISTINCT
使用示例