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

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

Table 1:

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

Table 2:

<
3条回答
  •  情深已故
    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.

提交回复
热议问题