我对SQL没有多少经验,我似乎无法弄清楚这个问题。
如果我有这样的表:
安装
id user
1 bob
2 carl
2 carl
2 charles
3 bill
3 bill
和另一个像这样:
应用
id name
1 app1
2 app2
3 app3
我怎么会得到这样的东西?:
name distinct_users
app1 1
app2 2
app3 1
我试过这个:
select apps.name, count(distinct installs.user)
from installs, apps
where installs.id = apps.id;
但这只会产生一行,因为它会计算安装中不同用户的总数。
app1 4
答案 0 :(得分:3)
您缺少group by
条款以获得每个应用的结果:
SELECT apps.name, COUNT(distinct installs.user)
FROM installs, apps
WHERE installs.id = apps.id;
GROUP BY apps.name
顺便说一下,隐式连接(在from
子句中有多个表已经被认为已经推荐了很长一段时间了。相反,它建议你使用一个显式的加入:
SELECT apps.name, COUNT(distinct installs.user)
FROM installs
JOIN apps ON installs.id = apps.id;
GROUP BY apps.name
答案 1 :(得分:2)
使用group by和count(*)
Select apps.name, count(*)
from installs
inner join apps on installs.id = apps.id
group by apps.name;
答案 2 :(得分:1)
您需要添加GROUP BY
更多的是避免使用逗号分隔的表格概念并将JOIN与ON一起使用
为每个表添加别名以提高可读性。
SELECT A.name, COUNT(DISTINCT I.user)
FROM apps A
INNER JOIN installs I ON I.id = A.id
GROUP BY A.name;
答案 3 :(得分:0)
SELECT `apps`.`name`, COUNT(DISTINCT(`installs`.`user`))
FROM `installs`, `apps`
WHERE `installs`.`id` = `apps`.`id`
GROUP BY `apps`.`id`;
请参阅此fiddle。