MySQL - How to display row value as column name using concat and group_concat

后端 未结 3 987
无人共我
无人共我 2020-12-06 23:14

Table 1:

id   | typeid | available|
0    | 1      | 12       |
0    | 2      | 44       |

Table 2:

<
相关标签:
3条回答
  • 2020-12-06 23:17

    Try this:

    SELECT a.id, MAX(IF(b.typename = 'CL', a.available, 0)) CL, 
           MAX(IF(b.typename = 'ML', a.available, 0)) ML
    FROM table1 a
    INNER JOIN table2 b ON a.typeid=b.typeid
    GROUP BY a.id;
    

    Use SUM function if you want to sum of the data from available column for particualr type else use the same query as ii is.

    0 讨论(0)
  • 2020-12-06 23:18

    You should use table pivoting. There is no PIVOT command in MySQL, so you can use this query -

    SELECT
      t1.id,
      MAX(IF(t2.typename = 'CL', t1.available, NULL)) AS CL,
      MAX(IF(t2.typename = 'ML', t1.available, NULL)) AS ML
    FROM table1 t1
      JOIN table2 t2
        ON t1.typeid = t2.typeid
    GROUP BY
      t1.id;
    

    MySQL pivot tables (transform rows to columns).

    Use GROUP_CONCAT function instead of MAX, if multiple available values are possible.

    0 讨论(0)
  • 2020-12-06 23:38

    It can be done only if you know all the typenames in advance -- otherwise, you'll need to find another way. In databases that support returning result sets from stored procedures, it could be done with a stored proc. But mysql doesn't support that.

    If you know all the typenames, here's how you build the query:

    SELECT
        id,
        SUM(IF(typename = 'CL', available, 0)) AS `CL`,
        SUM(IF(typename = 'ML', available, 0)) AS `ML`
    FROM table1 join table2 on table1.typeid = table2.typeid
    GROUP BY id
    
    0 讨论(0)
提交回复
热议问题