mysql 用行实现动态列,MYSQL,动态行到列

I have a table user that looks something like this (more columns involved)

user_id | user_name |

1 | adam |

2 | berta |

3 | caesar |

a table product that looks something like this

product_id | product_name |

1 | product 1 |

2 | product 2 |

3 | product 3 |

4 | product 4 |

and a table u_p that refers to products a user is allowed to use

u_p_id | u_p_user | u_p_prod |

1 | 1 | 1 |

2 | 1 | 2 |

3 | 2 | 3 |

where u_p_user and u_p_prod are the foreign keys to user_id resp. product_id.

What I want is this:

user_id | user_name | u_p_prod=1 | u_p_prod=2 | u_p_prod=3 | u_p_prod=4 |

1 | adam | 1 | 1 | 0 | 0 |

2 | berta | 0 | 0 | 1 | 0 |

3 | caesar | 0 | 0 | 0 | 0 |

users and products have to be dynamic, off course.

How can this be done in mySQL?

解决方案

This is often called a pivot. There's no way to do a pivot without hard-coding one column per distinct value. This means you need to know the set of distinct values before you write the SQL query.

SELECT u.user_id, u.user_name,

COALESCE(MAX(IF(u_p.prod=1, 1, 0), 0) AS `u_p_prod=1`,

COALESCE(MAX(IF(u_p.prod=2, 1, 0), 0) AS `u_p_prod=2`,

COALESCE(MAX(IF(u_p.prod=3, 1, 0), 0) AS `u_p_prod=3`,

COALESCE(MAX(IF(u_p.prod=4, 1, 0), 0) AS `u_p_prod=4`

FROM user AS u

LEFT OUTER JOIN u_p ON u.user_id = u_p.u_p_user

GROUP BY u.user_id;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值