MySQL上的Left Join + count + sum

时间:2016-04-30 09:14:49

标签: mysql join count sum

此问题与my previous question类似。但有几个变种(我有高级JOIN的探针,我在论坛中找不到任何有用的信息)。

同样,我更改了表格,字段和值的名称,只保留了数据库的结构供您理解。

现在,让我们假设我有这个(我不能改变结构):

ID | AGE | COUNTRY 
1  |  25 |   usa   
2  |  46 |   mex   

...

食品

ID | PERSON_ID | CATEGORY | FOOD       | UNITS
1  |     1     | fruit    | apple      |   2
2  |     1     | fruit    | grape      |  24
3  |     1     | fruit    | orange     |   5
3  |     1     | fast     | pizza      |   1
4  |     1     | fast     | hamburguer |   3
5  |     1     | cereal   | corn       |   2

...

但我在表people中有数百foods个关系,foods上有八个类别,每个类别有4到24个food

很好,目前我使用的代码与此类似:

SELECT p.*, SUM(f.units) as orapple
FROM people p
LEFT JOIN foods f
ON f.person_id = p.id
  AND f.food in('apple','orange')
WHERE p.id = 1
GROUP BY p.id

要得到这个:

ID | AGE | COUNTRY | ORAPPLE
1  |  25 |   usa   |    7

请注意,结果中的orappleunits上的数字之和,具体而言,food等于'orange'和'apple'。

现在,我需要它来添加每个类别的数量,例如,我需要这个:

ID | AGE | COUNTRY | ORAPPLE | FRUIT | FAST | CEREAL
1  |  25 |   usa   |    7    |   3   |  2   |   1   

1 个答案:

答案 0 :(得分:3)

使用

中的结果
SELECT DISTINCT category FROM foods;

构造以下查询:

SELECT p.*,
  SUM(CASE WHEN f.food in ('apple','orange') THEN f.units ELSE 0 END) as orapple,
  COUNT(f.category='fruit'  OR NULL) AS fruits,
  COUNT(f.category='fast'   OR NULL) AS fast,
  COUNT(f.category='cereal' OR NULL) AS cereal 
FROM people p
LEFT JOIN foods f
ON f.person_id = p.id
WHERE p.id = 1
GROUP BY p.id;

http://sqlfiddle.com/#!9/71e12/21

搜索网页或搜索以查找更多示例。