加入mysql计数

时间:2018-03-02 13:43:48

标签: mysql sql

所以我有两张桌子记录了用户最喜欢的食物类型:

users

 ------------
 id | country
 ------------
 1  | US
 2  | PH
 3  | US
 4  | US
 5  | PH

food_favourites

-----------------
food_id | user_id
-----------------
3       | 1
7       | 1
3       | 2
3       | 3
3       | 4

我想知道有多少来自美国标记为food_id 3的独特用户是他们的最爱。

到目前为止,我有这个问题:

select *, count(user_id) as total
from food_favourite
inner join users on users.id = food_favourites.user_id
where food_favourites.food_id = 3
and users.country = 'US'
group by users.id

那么这不起作用因为它将total返回到4而不是仅仅3。

我也尝试过子查询 - 没有运气,我想我错过了一些东西。

6 个答案:

答案 0 :(得分:2)

DROP TABLE IF EXISTS users;

CREATE TABLE users
(user_id SERIAL PRIMARY KEY
,country CHAR(2) NOT NULL
);

INSERT INTO users VALUES
(1,'US'),
(2,'EU'),
(3,'US'),
(4,'US'),
(5,'EU');

DROP TABLE IF EXISTS favourite_foods;

CREATE TABLE favourite_foods
(food_id INT NOT NULL
,user_id INT NOT NULL
,PRIMARY KEY(food_id,user_id)
);

INSERT INTO favourite_foods VALUES
(3,1),
(7,1),
(3,2),
(3,3),
(3,4);

SELECT COUNT(DISTINCT u.user_id) distinct_users
  FROM users u 
  JOIN favourite_foods f 
    ON f.user_id = u.user_id 
 WHERE u.country = 'US'
   AND f.food_id = 3;
+----------------+
| distinct_users |
+----------------+
|              3 |
+----------------+

答案 1 :(得分:1)

首先,上述问题的答案应为3,因为id 1,3,4都有food_id 3作为他们最喜欢的食物。

要打印查询,试试这个,它肯定会起作用:

volumes:
  /mnt/volume-part1:/volume
  conf:
  vhost:
  html:
  certs:

答案 2 :(得分:1)

  

我想知道有多少来自美国标记为food_id 3的独特用户是他们的最爱。

您使用COUNT DISTINCT计算唯一值:

select count(distinct ff.user_id) as total
from food_favourite ff
inner join users u on u.id = ff.user_id
where ff.food_id = 3
and u.country = 'US';

不要按用户分组,因为您不希望每个用户获得结果。你想要一行一个数字,告诉你有多少美国用户喜欢食物3。

我喜欢的另一种选择。查询读起来就像我会说出任务:计算来自美国的用户喜欢食物3。

select count(*) as total
from users
where country = 'US'
and id in (select user_id from food_favourites where food_id = 3);

没有不必要的连接,因此无需返回不同的值。

答案 3 :(得分:0)

尝试:

select count(user_id) as total
from food_favourites
inner join users on users.id = food_favourites.user_id
where food_favourites.food_id = 3
   and users.country = 'US'

答案 4 :(得分:0)

sub_query是

SELECT u.country, f.food_id,  COUNT(u.id) AS 'Total users'
FROM users u
INNER JOIN food_favourites AS f ON (u.id = f.[user_id])
WHERE u.country = 'US'
GROUP BY u.country, f.food_id

答案 5 :(得分:0)

select count(user_id) as total, Country
from food_favourites 
inner join users on users.id = food_favourites.user_id
where food_favourites.food_id = 3
and users.country = 'US'
group by country

未经测试,但我认为这是你之后的事情?这将仅返回美国的结果和3的食物ID。如果您想要更可重复使用的东西,您可以简单地遍历所有国家/地区的结果......这样的事情应该可行(再次,未经测试......):

select count(user_id) as total, Country, food_id
from food_favourites 
inner join users on users.id = food_favourites.user_id
group by country, food_id
order by country, food_id