douju2053 2019-02-19 09:33
浏览 27
已采纳

加入具有多个结果的表,然后合并为一列

First of all, i know my question heading is little bit or more confusing so let me try to explain.

I have 3 tables,

  1. Companies
  2. company_branches
  3. cities

so with those tables, i want to select all from companies and join company_branches then join cities.

All WITH JUST ONE SQL QUERY, and i want to end up with a list of companies, and each company having it's branches (array) under a column called branches.

See examples bellow.

companies_table

  id    |   name
--------+-----------------------
  1     |  microsoft
--------+-----------------------
  2     |  facebook



company_branches_table

  id    |   company_id    | city_id
--------+-----------------+-------------
  1     |  1              | 3
--------+-----------------+-------------
  2     |  1              | 2
--------+-----------------+-------------
  3     |  2              | 1


cities

  id    |   name     
--------+-------------
  1     |  LA              
--------+-------------
  2     |  New york
--------+-------------
  3     |  Chicago

Here is how i wanted my results to look like

in Json or associative array

[
   {
     id       : 1,
     name     : microsoft,
     branches : [
                  {
                     id    : 2,
                     city_name : New york
                  },   
                  {
                     id    : 3,
                     city_name : Chicago
                  }
                ]
   },
   {
     id       : 2,
     name     : facebook,
     branches : [
                  {
                     id    : 1,
                     city_name : LA
                  }   

                ]
   }

]

I hope u'll understand. thanks in advance


[Edit]


Listed tables at the top

  • 写回答

2条回答 默认 最新

  • dongtiao5094 2019-02-19 10:15
    关注

    Maybe this will help

    SELECT ct.id,ct.name,group_concat(c.id, '->', c.name) AS branches FROM companies_table AS ct JOIN company_branches_table AS cbt ON ct.id = cbt.company_id JOIN cities AS c ON c.id = cbt.city_id GROUP BY ct.id

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?