mysql 查询1对n,MySQL数据透视表1对n的关系

这篇博客探讨了如何使用SQL查询来实现数据的透视转换,特别是在处理表格数据时,将行转换为列的一种方法。通过示例展示了针对特定item_id(如001)时,如何从两个表`master_item`和`process`中提取数据,形成新的结果表格,其中proc_seq作为列名,显示对应的过程序号。
摘要由CSDN通过智能技术生成

I have data like this

table master_item

+-------+---------+

|item_id|item_name|

+-------+---------+

| 001 | Car A |

| 002 | Car B |

+-------+---------+

and relation into table process

+-------+--------+

|proc_id|proc_seq|

+-------+--------+

| 001 | 1 |

| 001 | 2 |

| 001 | 3 |

| 001 | 4 |

| 001 | 5 |

| 002 | 1 |

| 002 | 2 |

| 002 | 3 |

+-------+--------+

and i want result like this when i select item_id = 001

+-------+---------+-----+-----+-----+-----+-----+-----+-----+

|item_id|item_name|proc1|proc2|proc3|proc4|proc5|proc6|proc7|

+-------+---------+-----+-----+-----+-----+-----+-----+-----+

| 001 | Car A | 1 | 2 | 3 | 4 | 5 | | |

+-------+---------+-----+-----+-----+-----+-----+-----+-----+

what is the query to produce this result ?

解决方案

The problem lies in PIVOT TABLE category.

Here you can accomplish your result through the query given below:

SET @sql := '';

SELECT

CONCAT('SELECT

MI.item_id,

MI.item_name,',

GROUP_CONCAT('MAX(CASE WHEN P.proc_seq =', P.proc_seq ,' THEN P.proc_seq END) AS ', 'proc',P.proc_seq,' '),

'FROM master_item MI

INNER JOIN process P ON MI.item_id = P.proc_id

WHERE MI.item_id = 1

GROUP BY P.proc_id') INTO @sql

FROM master_item MI

INNER JOIN process P ON MI.item_id = P.proc_id

WHERE item_id = 1

GROUP BY P.proc_id;

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE stmt;

But like I said, better do this kind of job in application logic. Otherwise it will be too cumbersome to make it done through MySQL alone.

EDIT:

In order to get result for each item_id

SET @sql := '';

SELECT

CONCAT('SELECT

MI.item_id,

MI.item_name,',

GROUP_CONCAT('MAX(CASE WHEN P.proc_seq =', P.proc_seq ,' THEN P.proc_seq END) AS ', 'proc',P.proc_seq,' '),

'FROM master_item MI

INNER JOIN process P ON MI.item_id = P.proc_id

GROUP BY P.proc_id') INTO @sql

FROM master_item MI

INNER JOIN process P ON MI.item_id = P.proc_id

WHERE

item_id = (

SELECT

maxProcId.proc_id

FROM

(

SELECT

proc_id,

COUNT(proc_seq) total

FROM process

GROUP BY proc_id

ORDER BY total DESC

LIMIT 1

) AS maxProcId

)

GROUP BY

P.proc_id;

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE stmt;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值