Create MySQL view using distinct values as columns

℡╲_俬逩灬. 提交于 2019-12-06 04:34:27

Result sets with a variable number of columns are usually a bad idea, however if you really want to do it then you can use a combination of GROUP BY, MAX and IF:

CREATE VIEW yourview AS
SELECT
    date,
    MAX(IF(name = 'm1', status, NULL)) m1,
    MAX(IF(name = 'm2', status, NULL)) m2,
    MAX(IF(name = 'm3', status, NULL)) m3
FROM yourtable
GROUP BY date;

The view will give you this data, as you wanted:

date        m1       m2       m3    
2011-01-01  online   offline  online
2011-01-02  offline  offline  online

Note that it is not possible to create a view with a variable number of columns so you will have to recreate the view every time the number of columns changes.

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