好的,首先,我要更改表格,字段和值的名称,我只是保留数据库的结构供您理解。
现在,让我们假设我有一个表people
,其中包含字段id
,age
,country
和language
。另一张表格foods
,其中包含每个人在people
吃饭的食物,字段:person_id
,food
,units
。
注意:food
是char
,而不是另一个表的ID,我无法更改此结构。
现在,让我们提供一些数据:
ID | AGE | COUNTRY | LANGAGE
1 | 25 | usa | en
2 | 46 | mex | es
ID | PERSON_ID | FOOD | UNITS
1 | 1 | apple | 2
2 | 1 | grape | 24
3 | 1 | pizza | 1
4 | 2 | apple | 3
5 | 2 | pizza | 2
很好,我需要的是获取id
,age
,country
以及某人吃掉的apple
和grape
的总和(忽略pizza
)。在这个例子中,如果我寻找ID 1,我应该得到:
ID | AGE | COUNTRY | UNITS
1 | 25 | usa | 26
对于ID 2:
ID | AGE | COUNTRY | UNITS
2 | 46 | mex | 3
答案 0 :(得分:1)
select p.id, p.age, p.country, sum(f.units) as units
from people p join foods f
on (p.id = foods.person_id and f.food in ('apple', 'grape'))
group by p.id, p.age, p.country
如果您需要其他食物组合,只需编辑in
条款的内容。
答案 1 :(得分:1)
http://sqlfiddle.com/#!9/38304/2
SELECT p.*, SUM(f.units)
FROM people p
LEFT JOIN foods f
ON f.person_id = p.id
AND f.food in('apple','grape')
GROUP BY p.id
答案 2 :(得分:0)
SELECT p.Id, p.Age,p.country, sum(f.units)
FROM people AS p
INNER JOIN foods AS f ON f.person_id = p.id
WHERE f.food <> 'Pizza'
GROUP BY p.id,p.age,p.country
答案 3 :(得分:0)
select p.id, p.age, p.country, sum(f.units) as units
from people p
join foods f on f.person_id = p.id
where f.food <> 'Pizza'
group by p.id, f.food
答案 4 :(得分:0)
select
t1.id, t1.age, t1.country, sum(t2.units)
from people as t1, foods as t2
where
t1.id = t2.person_id and t2.food != 'pizza'
group by t1.id
order by t1.id