I have 3 tables:
customers:
_______________
| id | name |
|-----|-------|
| 1 | John |
| 2 | Adam |
| 3 | Smith |
---------------
cities:
__________________
| id | city |
|-----|----------|
| 1 | LA |
| 2 | PHI |
| 3 | HOU |
| 4 | DET |
------------------
customers_cities:
________________________________
| id | customer_id | city_id |
|-----|--------------|----------
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 3 | 2 |
| 5 | 1 | 3 |
--------------------------------
I wanted to aggregate and show in a json format all the cities and their customers listed in them. Some customers can be in different cities too.
Output should look like:
- LA:
|- John
- PHI
|- John
|- Smith
- Hou
|- Adam
|-John
The JSON output looks like this:
"data":{
"customers_in_cities": [
"LA" : [
{
"id": 1,
"name": "John"
}],
"PHI" : [
{
"id": 1,
"name": "John"
},
{
"id": 3,
"name": "Adam"
}],
"HOU" : [
{
"id": 3,
"name": "Adam"
},
{
"id": 1,
"name": "John"
}],
]
}
Something like the above json output.
I tried:
SELECT cus.name AS customer_name, cty.city AS city_name
FROM cities cty
INNER JOIN customers_cities cc ON cc.city_id = cty.id
INNER JOIN customers cus ON cc.customer_id = cus.id;
will appreciate any help