I am trying to join 6 different tables using MySQL but some tables have nested or many items. I am trying to get these tables to look a little something like the JSON example below.
I don't know of any good database modeling/schema software or app so here are my tables in plain text. If you have any recommendations there, that would be great to hear but my main question is finding a way to join these tables in a nested format. PS I'm on OSX
Here are my tables
/**
* survey_tbl <- has many
* survey_vs_template_tbl
* template_items_tbl <- has many
* items_tbl
* template_item_response_tbl <- has many
* responses_tbl
**/
So in a pseudo format, the sql should
- Search for many surveys
- Loop though each survey and match it to the correct template
- Then get many items in template form
- Looping though each template, find the matching item
- Then get many response templates
- Finally, loop though each of those response templates to find the response
So I have the SQL to receive all this data using JOINS but nesting this into arrays is my issue.
$sql = "SELECT * FROM survey_tbl
INNER JOIN survey_vs_template_tbl ON survey_vs_template_tbl.survey_id = survey_tbl.survey_id
INNER JOIN template_items_tbl ON template_items_tbl.template_id = survey_vs_template_tbl.template_id
INNER JOIN items_tbl ON items_tbl.item_id = template_items_tbl.template_id
LEFT OUTER JOIN template_item_response_tbl ON template_item_response_tbl.template_item_id = template_items_tbl.template_item_id
LEFT OUTER JOIN responses_tbl ON responses_tbl.response_id = template_items_tbl.template_id
WHERE client_id='{$this->userId}'";
Here is my JSON example. The only use template tables have are to match corresponding templates to the actual item.
{
"surveys": [
{
"name": "some random survey",
"due": "03/01/2016",
"items": [
{
"itemId": 1,
"itemTitle": "Did you have a good day?",
"responses": [
{
"responseId": 1,
"responseText": "Yes"
},
{
"responseId": 2,
"responseText": "No"
}
]
}
]
}
]
}
I know I could loop though this data and join what I can, I just feel SQL would have some sort of nesting capability.