简体   繁体   English

PHP / MySQL的:多列加入结果到1 PHP行

[英]php / mysql: multi column JOIN result into 1 php row

Please consider this MySQL table structure: 请考虑以下MySQL表结构:

table1:
id,name

table2:
table1_id,type, value

I am trying to get all names in table1 and all corresponding types and their average values in table2. 我正在尝试获取表1中的所有名称以及表2中的所有对应类型及其平均值。 "type" could be 1 of 3 fixed values: “类型”可以是3个固定值中的1个:

SELECT table1.name ,
AVG(table2.value) as avgvalue,
FROM table1 as table1 
LEFT OUTER JOIN table2 as table2 ON table1.id=table2.table1_id
GROUP BY table1.name,table2.type

Result: 结果:

name | type | avgvalue
-----+------+-------
name1| type1| value1
-----+------+-------
name1| type2| value2
-----+------+-------
name2| type1| value2
-----+------+-------

My goal is to list each name and all types/average values in one row in a (HTML-)table, regardless if a type / averagevalue exists or not. 我的目标是在(HTML-)表的一行中列出每个名称和所有类型/平均值,而不管是否存在类型/平均值。

So what I would need is something like: 所以我需要的是:

name | type1| type2 |type 3|
-----+------+---------------
name1|value1| value2|      |
-----+------+-------+------+
name2|value2|       |      |
-----+------+-------+------+

My question: Should I use SQL or php to modify the results in order to list all types for a particular name? 我的问题:我应该使用SQL或php修改结果以便列出特定名称的所有类型吗?

If SQL, how? 如果是SQL,怎么办? Is my LEFT OUTER JOIN even the right way? 我的LEFT OUTER JOIN JOIN是否正确?

If PHP, what would be the best practice there? 如果是PHP,那里的最佳实践是什么?

Thanks for any help 谢谢你的帮助

You can use the following technique for generating the pivot table as 您可以使用以下技术来生成数据透视表:

select 
t1.name,
max(case when t2.type = 'type1' then t2.value end) as `type1`,
max(case when t2.type = 'type2' then t2.value end) as `type2`,
max(case when t2.type = 'type3' then t2.value end) as `type3`
from table1 t1
left join table2 t2 on t2.table1_id = t1.id
group by t1.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM