I am a bit confused about using GROUP_CONCAT in MySQL.
To explain, I am working on a listings directory, sort of like Yelp for example. A user filters different criteria and is returned with different places.
For example, if a user wants to see all places that have been categorized (or tagged) as "Restaurant", or maybe "Lounge" then they will see only those places, but also they should be presented with any other tagged categories.
To do this, I have built some tables in my database. The main tables that relate to this question are the tables places
and categories
and place_category_rel
as such:
places table:
+----+------------------+
| id | name |
+----+------------------+
| 1 | Johns Restaurant |
+----+------------------+
| 2 | Jims Place |
+----+------------------+
| 3 | Cafe Luna |
+----+------------------+
place_category_rel table
+----------+-------------+
| place_id | category_id |
+----------+-------------+
| 1 | 1 |
+----------+-------------+
| 1 | 2 |
+----------+-------------+
categories table
+----+------------+
| id | name |
+----+------------+
| 1 | Lounge |
+----+------------+
| 2 | Restaurant |
+----+------------+
| 3 | Night Club |
+----+------------+
To obtain all places I use the following query:
SELECT p.id,
p.name,
group_concat(DISTINCT cat.name separator ',') as categories
FROM places p
LEFT JOIN places_categories_rel rel ON p.id=rel.place_id
LEFT JOIN categories cat ON cat.id=rel.category_id
GROUP BY p.id
Which gets me this result set:
+----+------------------+--------------------+
| id | name | categories |
+----+------------------+--------------------+
| 1 | Johns Restaurant | Lounge,Restaurant |
+----+------------------+--------------------+
| 2 | Jims Place | Null |
+----+------------------+--------------------+
| 3 | Cafe Luna | Null |
+----+------------------+--------------------+
The above works great. However, when I add a WHERE clause to filter down on places that are categorized as "Lounge" , I lose the other category:
SELECT p.id,
p.name,
group_concat(DISTINCT cat.name separator ',') as categories
FROM places p
LEFT JOIN places_categories_rel rel ON p.id=rel.place_id
LEFT JOIN categories cat ON cat.id=rel.category_id
WHERE cat.name = 'Lounge'
GROUP BY p.id
Result:
+----+------------------+------------+
| id | name | categories |
+----+------------------+------------+
| 1 | Johns Restaurant | Lounge |
+----+------------------+------------+
what I would like is this result set instead:
+----+------------------+--------------------+
| id | name | categories |
+----+------------------+--------------------+
| 1 | Johns Restaurant | Lounge, Restaurant |
+----+------------------+--------------------+
Can someone point me in the right direction? Thanks.