doucuyu2259 2015-07-24 01:55
浏览 53

使用MySQL JOINS创建嵌套或多维数组

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

  1. Search for many surveys
  2. Loop though each survey and match it to the correct template
  3. Then get many items in template form
  4. Looping though each template, find the matching item
  5. Then get many response templates
  6. 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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号