简体   繁体   中英

Join a table that have multiple results, then merge into one column

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

也许这会有所帮助

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

you can use group_concat()

    SELECT c.NAME                AS companyName, 
       Group_concat(ci.NAME) AS totalBranches 
FROM   companies_table c 
       INNER JOIN company_branches_table cb 
               ON cb.company_id = c.id 
       INNER JOIN cities ci 
               ON ci.id = cb.city_id 
GROUP  BY c.NAME

simple approach...

   SELECT c.NAME, 
       ci.NAME 
FROM   companies_table c 
       INNER JOIN company_branches_table cb 
               ON cb.company_id = c.id 
       INNER JOIN cities ci 
               ON ci.id = cb.city_id

both query is working properly tried in MySQL database...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM