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

时光怂恿深爱的人放手 提交于 2019-11-26 23:33:45

问题


Table 1:

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

Table 2:

typeid   | typename   |
1        | CL          |
2        | ML          |

I have a query using concat and group_concat:

select id,concat(group_concat(typename,available)) as types from table1
join table2 on table2.typeid=table1.typeid

I got the result as:

id | types   | 
0  | CL12,ML44 |

But I want to display it like this:

id   | CL   | ML    |
0    | 12   | 44    |

Is there any way to split the group_concat result to columns heads?

I want dynamically fetch data from table2. Some user can add data to table2. So hard-coding typename is not possible.


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/13985470/mysql-how-to-display-row-value-as-column-name-using-concat-and-group-concat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!