我有三张表,如下面的
应用:
+----+------+--------+
| id | name | author |
+----+------+--------+
| 1 | App1 | 1 |
| 2 | App2 | 1 |
| 3 | App3 | 1 |
+----+------+--------+
安装:
+-----+----+---------------------+
| app | id | timestamp |
+-----+----+---------------------+
| 3 | 1 | 2017-01-27 19:12:05 |
+-----+----+---------------------+
用户:
+----+----------+-------------------+--------------------------------------------------------------+
| id | username | email | password |
+----+----------+-------------------+--------------------------------------------------------------+
| 2 | name | email@address.com | |
+----+----------+-------------------+--------------------------------------------------------------+
每当有人安装应用程序时,它都会添加到安装表中并加盖时间戳。
我知道我可以通过
获得个人应用的安装SELECT a.name,COUNT(b.id) as installs FROM applications a,installs b WHERE a.id=3 AND b.app=3;
我会得到
+------+----------+
| name | installs |
+------+----------+
| App3 | 30000 |
+------+----------+
我想要的是能够在一个结果集中获取应用程序的所有名称以及某个作者的应用程序安装,如下所示:
+------+----------+
| name | installs |
+------+----------+
| App1 | 10000 |
| App2 | 20000 |
| App3 | 30000 |
+------+----------+
答案 0 :(得分:3)
这实际上是GROUP BY
和JOIN
的基本WHERE
查询:
SELECT a.name, COUNT(i.id) as installs
FROM applications a LEFT JOIN
installs i
ON a.id = b.app
WHERE a.author = 1
GROUP BY a.name;
注意:
FROM
子句中使用逗号。 始终使用正确的JOIN
语法。b
这样的随机字母。JOIN
条件使用两个表中的列。LEFT JOIN
也会为作者保留所有应用程序。答案 1 :(得分:2)
使用INNER JOIN
而不使用过滤器
SELECT a.NAME,
Count(*) AS installs
FROM applications a
JOIN installs i
ON a.id = i.app