加入两个表和Pivot

时间:2017-02-05 14:21:58

标签: mysql sql pivot

抱歉,我确定这是一个重复的问题,但我不知道如何搜索我的问题。 我想将两个表(如wordpress post和post_metas)连接到第三个矩阵。

我正在使用MySQL + PHP

更新 感谢第一批解决方案,我正在寻找最佳解决方案。所以如果不推荐使用mysql,你可以推荐我另一个关于PHP的解决方案。

我需要最顺畅的解决方案。也许你可以帮我找到:) 谢谢你们!

FOODS

+----+-----------+
| id | Food name |
+----+-----------+
|  1 | Apple     |
|  2 | Banana    |
|  3 | Milk      |
+----+-----------+

NUTRITIONS

+----+---------+-----------+-------+
| id | food_id |   name    | value |
+----+---------+-----------+-------+
|  1 |       1 | energy    |  1    |
|  2 |       1 | glucose   |  11   |
|  3 |       1 | fructose  |  4    |
|  4 |       2 | energy    |  36   |
|  5 |       2 | glucose   |  112  |
|  6 |       2 | b-vitamin |  67   |
|  7 |       2 | sucrose   |  3    |
|  8 |       3 | fat       |  6    |
|  9 |       3 | calcium   |  66   |
| 10 |       3 | energy    |  77   |
+----+---------+-----------+-------+

我想要这样的事情:

+--------+--------+---------+----------+-----------+---------+-----+---------+
|  Food  | energy | glucose | fructose | b-vitamin | sucrose | fat | calcium |
+--------+--------+---------+----------+-----------+---------+-----+---------+
| Apple  |      1 |      11 |        4 |         0 |       0 |   0 |       0 |
| Banana |     36 |     112 |        0 |        67 |       3 |   0 |       0 |
| Milk   |     77 |       0 |        0 |         0 |       0 |   6 |      66 |
+--------+--------+---------+----------+-----------+---------+-----+---------+

1 个答案:

答案 0 :(得分:0)

以下查询将起作用:

select f.foodname,
        max(case when n.name='energy' then value else 0 end)energy,
        max(case when n.name='glucose' then value else 0 end)glucose,
        max(case when n.name='fructose' then value else 0 end)fructose,
        max(case when n.name='b-vitamin' then value else 0 end)b_vitamin,
        max(case when n.name='sucrose ' then value else 0 end)sucrose ,
        max(case when n.name='fat ' then value else 0 end)fat ,
        max(case when n.name='calcium ' then value else 0 end)calcium 
from foods f,
     nutritions n
where f.id=n.food_id     
group by f.foodname