mysql 动态选择字段,如何从mysql中的表创建选择动态字段?

I have query join in select statement like this :

select a.item_number, total_quantity, store, factory

from (

select item_number, sum(quantity) as "total_quantity"

from `item_details`

group by item_number

) `a`

left join (

select item_number, sum(quantity) as 'store'

from `item_details` where location_code = 'STORE'

group by item_number

) `b` on `a`.`item_number` = `b`.`item_number`

left join (

select item_number, sum(quantity) as 'factory'

from `item_details`

where location_code = 'FACTORY'

group by item_number

) `c` on `a`.`item_number` = `c`.`item_number`

order by `item_number` asc

From the query above, it appears if I use table item_details with fields id, item_no, quantity and location_code

If the query executed, the result like this :

869b4024c7c7b45dc6f366ee44fcdab1.png

The results are correct. But here I want to create field store and factory to be dynamic. So it's taken from table locations. Because the data location is dynamic. It can be added and removed

So I have table locations with field id and description like this :

1857cd49517f81e3204de67da915446f.png

field location_code in the item_details table is foreign key to field id in locations table

So how to create select dynamic fields from location table?

Note :

I use "query join in select statement" because I didn't have table locations before. Now I use table locations. Because the data in the location table is dynamic. It can be added and removed. So I want to display it like table 1 above with table location. Seems it need to join the table. But i'm still confused to do it

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值