关于MySQL的Left Join + count + sum

时间:2022-10-18 20:35:54

This question is similar to my previous question. But with several variants (I have probems with advanced JOINs and I couldn't find any usefull info in the forum).

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

Again, I changed the name of the tables, fields and values, keeping just the structure of my data base for you to understand.

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

Now, let's suppouse I have this (and I can't change the structure):

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

.

People

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

...

.

Foods

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

...

.

But I have hundreds of people all with their relation in table foods, about eight categories on foods and each category has 4 to 24 food.

但我有数百人在餐桌食品方面有关系,大约有8类食品,每类食品有4到24种。

Fine, currently I am using a code similar to this one:

很好,目前我正在使用类似于这个的代码:

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

To get this:

要得到这个:

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

Note that orapple in the result is the sum of the numbers on units, specifically, where food is equal to 'orange' and 'apple'.

请注意,结果中的orapple是单位数的总和,具体而言,食物等于'orange'和'apple'。

Now, what I need it to add the number of each category, example, I need this:

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

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

1 个解决方案

#1


3  

Use the result from

使用结果

SELECT DISTINCT category FROM foods;

to construct the following query:

构造以下查询:

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

Search the web or SO for to find more examples.

搜索网络或SO搜索pivot-table以查找更多示例。

#1


3  

Use the result from

使用结果

SELECT DISTINCT category FROM foods;

to construct the following query:

构造以下查询:

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

Search the web or SO for to find more examples.

搜索网络或SO搜索pivot-table以查找更多示例。