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

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

Table 1:

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

Table 2:

<
3条回答
  •  执笔经年
    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
    

提交回复
热议问题