I have a MySQL database with a few tables. They look something like this –
The food table:
+----------+------------+--------------+
| username | date | food |
+----------+------------+--------------+
| test123 | 2012-09-16 | rice |
| test123 | 2012-09-16 | pizza |
| test123 | 2012-09-16 | french fries |
| test123 | 2012-09-16 | burger |
+----------+------------+--------------+
The main table:
+----------+------------+----------------+---------------+-------------+-------------+
| username | date | water_quantity | water_chilled | smoked_what | smoke_count |
+----------+------------+----------------+---------------+-------------+-------------+
| test123 | 2012-09-16 | 1 | no | cigarettes | 20 |
+----------+------------+----------------+---------------+-------------+-------------+
When I use the query SELECT * FROM main,food WHERE main.date=food.date;, I get four rows as a result. How would it be possible that I get the results in a single row? Ultimately, when I encode the results into JSON, I want it to look something like this –
[
{
"username":"test123",
"date":"2012-09-16",
"water_quantity":"1",
"water_chilled":"no",
"smoked_what":"cigarettes",
"smoke_count":"20",
{
"food":"rice",
"food":"pizza",
"food":"french fries",
"food":"burger",
},
}
]
or something similar to. I am a newbie to MySQL and databases in general and also to JSON.. Thanks in advance for the help.
Of course you can change what fields you select to control the output but that will solve your duplication issue.
As for the nested list of foods within the result set, you can use GROUP_CONCAT
SEE: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
I will see if I can recreate for demo
DEMO: