Question

I think that is my last question for today :D

I have the tables restaurant, food and a helper table, which just have the ids of both tables. If I'm doing now this:

SELECT * FROM restaurants
LEFT JOIN ResFoodHelper ON restaurants.id = ResFoodHelper.resId

The output is now the restaurants with a foodId. But if he finds more than 1 food for the restaurant, then i get for each food, which found, an extra output with the same restaurant.

Now it's like this:

If 1 Entry is available:

Restaurant 1 - FoodId 1
Restaurant 2 - FoodId 1
Restaurant 3 - FoodId 2

But if more than 1 found:

Restaurant 1 - FoodId 1
Restaurant 1 - FoodId 2
Restaurant 1 - FoodId 3
Restaurant 2 - FoodId 1
Restaurant 2 - FoodId 2
...

But I want something like this:

Restaurant 1 - FoodId 1, FoodId 2, FoodId 3
Restaurant 2 - FoodId 1, FoodId 2
Was it helpful?

Solution

Haven't tested but try something like this:

SELECT restaurants.id, GROUP_CONCAT(ResFoodHelper.id) 
FROM restaurants
LEFT JOIN ResFoodHelper ON restaurants.id = ResFoodHelper.resId
GROUP BY restaurants.id

OTHER TIPS

You need to join your food table as well and then you can use GROUP_CONCAT which will give you the comma seperated list of foods per restaurant ,also not sure for the column names so i just put them as example make sure you use right columns in query

SELECT r.name,
GROUP_CONCAT(f.name) `foods`
FROM  restaurants r 
LEFT JOIN ResFoodHelper rsf ON r.id = rsf.resId
LEFT JOIN food f ON f.id = rsf.food_id
GROUP BY r.id

Be ware of that fact it has a default limit of 1024 characters to concat but it can be increased which is defined in manual

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top