加入多个表并将表格的行显示为具有相同表格

时间:2018-06-11 12:17:17

标签: mysql sql

我有这样的多个表:

table

如果我使用' where table1.id = 1'我希望结果如图所示。 :

  • table2是列名称的商店值和键

  • table3是我需要显示的商店列名称

结果应为

ID | Name | A | B | C
1  | a | 10 | 20 | 30

1 个答案:

答案 0 :(得分:1)

条件侵略需要JOIN

select t1.id, t1.name, 
       sum(case when t3.name = 'a' then t2.value else 0 end) as A,
       sum(case when t3.name = 'b' then t2.value else 0 end) as B,
       sum(case when t3.name = 'c' then t2.value else 0 end) as C
from table1 t1 inner join 
     table2 t2
     on t2.table1_id = t1.id inner join
     table3 t3
     on t3.key_id = t2.key
where t1.id = 1
group by t1.id, t1.name;

但是,如果您想要使用动态方式,那么这将只使用已知值的聚合,那么您可能需要在MySQL中使用编程方法。