How to create select dynamic fields from a table in mysql?

后端 未结 2 850
忘掉有多难
忘掉有多难 2020-12-12 04:26

I have query join in select statement like this :

select a.item_number, total_quantity, store, factory
from (
    select item_number, sum(quantity) as \"tot         


        
相关标签:
2条回答
  • 2020-12-12 04:56

    If you are using stored procedure then your query will become easy to use dynamically. Dynamic column name you can manage by integer number or name of columns.
    store your existing query in the variable and use If condition to concat your dynamic query in variable. at last execute the statement by defined variable.

    you can take reference from below link for execute the dynamic code. mysql dynamic query in stored procedure

    0 讨论(0)
  • 2020-12-12 05:11

    This is not tested ,create a fiddle if you find errors.

    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'ifnull(SUM(case when location_code = ''',
          location_code ,
          ''' then quantity end),0) AS `',
          location_code , '`'
        )
      ) INTO @sql
    FROM
      item_details;
    SET @sql = CONCAT('SELECT item_number,SUM(quantity) as "total_quantity", ', @sql, ' 
                      FROM item_details
                       GROUP BY item_number');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    
    DEALLOCATE PREPARE stmt;
    
    0 讨论(0)
提交回复
热议问题