在两个表上使用Where和Count

时间:2015-05-15 17:16:56

标签: mysql count where

我有两张桌子

Foods
----------
ID    Name
----------
1. Chips
2. Pizza
3. Fish
4. Pasta

People
-----------------
ID Name    FoodID
-----------------
1. Robert       3
2. Norman       2
3. Leonard      4
4. Huey         3

我应该做的是找回属于不止一个人的任何食物。现在我应该通过COUNT和WHERE来做到这一点。可能需要进行INNER JOIN。

应该很简单,但我只是没有看到它。

3 个答案:

答案 0 :(得分:1)

select f.name, p.name, count(f.id) as total from foods f, people p 
where (f.id = p.FoodID)
group by f.name
having total > 1
order by f.name

http://sqlfiddle.com/#!9/b2a63/10

答案 1 :(得分:1)

您想要在公共字段上加入表格。 WHERE用作内连接。然后GROUP BY Foods.name按食物类型聚合行。 Count是一个总是与GROUP BY一起使用的聚合运算符。

SELECT Foods.Name, Count(*)
FROM Foods, People
WHERE Foods.ID = People.Food
GROUP BY Foods.Name
HAVING COUNT(*)>1;

如果您只想要食物清单,请省略第一次计数(*)。

答案 2 :(得分:-1)

select * from food inner join people  on people.id = food.id group by people.name