MySQL 将多对多连接为单行
我知道必须有一种方法可以做到这一点,但对于我的一生,我无法弄清楚:
我有 3 个表想要连接在一起(简化说明):
users
uid mail
1 [email protected]
2 [email protected]
3 [email protected]
profile_fields
fid name label
1 full_name Full Name
2 phone Phone
profile_values
uid fid value
1 1 Q Q
1 2 5555555555
2 1 Ww Ww
3 2 4444525411
我想获得以下结果形式:
uid mail full_name phone
1 [email protected] Q Q 5555555555
2 [email protected] Ww Ww NULL
3 [email protected] NULL 44445454111
我尝试过具有不同 JOIN 条件的各种 SELECT,但我似乎无法弄清楚如何让 profile_fields 的行成为我的 SELECT
编辑中的列:我也尝试过谷歌搜索,但我不能似乎弄清楚如何向谷歌表达这一点。
I know there's got to be a way to do this, but for the life of me I can't figure it out:
I have 3 tables I want to join together (simplified to illustrate):
users
uid mail
1 [email protected]
2 [email protected]
3 [email protected]
profile_fields
fid name label
1 full_name Full Name
2 phone Phone
profile_values
uid fid value
1 1 Q Q
1 2 5555555555
2 1 Ww Ww
3 2 4444525411
I'd like to get results of the form:
uid mail full_name phone
1 [email protected] Q Q 5555555555
2 [email protected] Ww Ww NULL
3 [email protected] NULL 44445454111
I've tried various SELECTs with different JOIN conditions but I can't seem to figure out how to get the rows of profile_fields to be my columns in my SELECT
EDIT: I've also tried googling around, but I can't seem to figure out how to phrase this to google.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
Use:
您尝试做的事情称为枢轴。 MySQL 本身不支持旋转,但您可以使用 OMG Ponies 发布的查询来实现。
但是,如果您必须支持任意数量的配置文件字段,则必须动态构建 SQL。
What you are trying to do is called a pivot. MySQL doesn't support pivoting natively, but you can do it using the query OMG Ponies posted.
However, if you have to support an arbitrary number of profile fields, you would have to build the SQL dynamically.
我认为一般来说你不能做你想做的事。即使 @OMG Ponies 示例是正确的,它也不适用于 profile_field 名称的其他值。
您可以尝试编写一些代码来根据实际的 profile_fields 生成对 profile_fields 的不同值的查询。
或者您可以进行简单的多对多连接并分析其他程序/代码中的数据。
I think that in general you can't do what you want. Even if @OMG Ponies example is correct it won't work for other values of profile_field names.
You can try writing some code to generate a query for different values of profile_fields based on actual profile_fields.
Or you can make simple many-to-many join and analyse data in other program/code.