Combine multiple rows into one row MySQL

后端 未结 2 2111
鱼传尺愫
鱼传尺愫 2020-12-10 04:12

Say I have two tables in a MySQL Database.

Table 1:

ID    Name
1     Jim
2     Bob
3     John

Table 2:

ID    key            


        
2条回答
  •  一生所求
    2020-12-10 04:38

    You have a structure called entity-attribute-value in the second table. There are two ways to do the combination. I think the aggregation method is the easier to express:

    select t1.name,
           max(case when `key` = 'address' then value end) as address,
           max(case when `key` = 'city' then value end) as city,
           max(case when `key` = 'region' then value end) as region,
           max(case when `key` = 'country' then value end) as country,
           max(case when `key` = 'postal_code' then value end) as postal_code,
           max(case when `key` = 'phone' then value end) as phone
    from table1 t1 left join
         table2 t2
         on t1.id = t2.id
    group by t1.name;
    

    The second method is to do separate joins for each value:

    select t1.name, address.value, city.value, . . .
    from table1 t1 left join
         table2 address
         on t1.id = address.id and address.`key` = 'Address' left join
         table2 city
         on t1.id = city.id and city.`key` = 'City' . . .
    

    Depending on the structure of the data, the join method can actually be faster in MySQL when it uses appropriate indexing. (Other databases have been algorithms for aggregation, so the group by method often works well in other databases.)

提交回复
热议问题