如何在SQL中使用WHERE进行计数和选择?

时间:2019-03-11 05:28:23

标签: mysql

我有两个表usergroup,还有一个usergroup作为链接表,其中包含组中存在的用户。

user

+-----+-------+
| id  | name  |
+-----+-------+
| U12 | John  |
| U13 | Rick  |
| U14 | Morty |
| U15 | Alex  |
| U16 | Felix |
+-----+-------+

group

+-----+--------+--------+
| id  |  name  | points |
+-----+--------+--------+
| G12 | Red    |     11 |
| G13 | Blue   |     22 |
| G14 | Green  |     55 |
| G15 | Yellow |     64 |
| G16 | Orange |     23 |
+-----+--------+--------+

usergroup

+----+---------+----------+
| id | user_id | group_id |
+----+---------+----------+
|  1 | U12     | G12      |
|  2 | U14     | G12      |
|  3 | U15     | G12      |
|  4 | U15     | G15      |
|  5 | U12     | G13      |
+----+---------+----------+

要选择特定用户所在的组,我可以这样做

SELECT group.*
FROM usergroup 
INNER JOIN group 
ON group.id = usergroup.group_id 
WHERE usergroup.user_id = ?

但是如何同时选择同一组中的用户总数

预期的样本输出-用户U12所在的组以及用户总数

+-----+------+--------+-------------+
| id  | name | points | users_count |
+-----+------+--------+-------------+
| G12 | Red  |     11 |           3 |
| G13 | Blue |     22 |           1 |
+-----+------+--------+-------------+

4 个答案:

答案 0 :(得分:1)

使用标量子查询

SELECT `group`.* , (select count(id) from usergroup a where a.group_id=usergroup.group_id ) as user_count
FROM usergroup 
INNER JOIN `group` ON `group`.id = usergroup.group_id 
WHERE usergroup.user_id = 'U12'

答案 1 :(得分:0)

SELECT y.id, y.name, y.points, y.users_count
FROM usergroup x INNER JOIN
    ( SELECT b.id, b.name, b.points, count(a.user_id) as users_count
    FROM usergroup a INNER JOIN group b
    ON a.group_id = b.id
    GROUP BY b.id ) AS y
ON x.group_id = y.id
WHERE x.user_id = 'U12'

答案 2 :(得分:0)

SELECT a.group_id,
       a.NAME,
       a.points,
       c.user_count
FROM   group a,
       usergroup b,
       (SELECT x.group_id,
               Count(*) AS user_count
        FROM   usergroup x
        GROUP  BY x.group_id) c
WHERE  a.group_id = b.group_id
       AND a.group_id = c.group_id
       AND user_id = 'U12'; 

答案 3 :(得分:-2)

SELECT group.*, count(usergroup.group_id),usergroup.user_id
FROM usergroup 
INNER JOIN group 
ON group.id = usergroup.id 
GROUP BY usergroup.group_id
Having usergroup.user_id = 'U12'

您需要结合使用分组。 在SQLFiddle上检查它:sqlfiddle.com /#!9 / b63e13 / 3/0