1

我在 mySql 数据库中有两个表,如下所示:

组:

| IDGroup| IDRat| Type| Category|
| 708    | 354  | 1   | A       |
| 709    | 354  | 1   | C       |

IDGroup主键在哪里。

用户:

| IDUser| Name| Surname | IDGroup |
| 1     | John| Doe     | 708     |
| 2     | Mick| Caine   | 708     |

主键在哪里IDUser

我想创建一个查询,接收 IDRat 作为参数并返回如下结果:

| IDGroup| Type| Category | Number_of_Users_in_this_group |

其中,顾名思义,第四列代表与该组关联的用户数。

例如通过IDRat = 354我想要获得以下结果:

| IDGroup| Type| Category | Number_of_Users_in_this_group |
| 708    | 1   | A        | 2                             |
| 709    | 1   | C        | 0                             |
4

3 回答 3

4

以下查询执行您想要的操作:

SELECT g.IDGroup, g.Type, g.Category, COUNT(u.IDGroup) 
FROM GROUPS g left join
     USERS u
     on g.IDGroup = u.IDGroup 
WHERE IDRat = XXX
GROUP BY g.IDGroup;

left join保留所有组。没有匹配时将count()返回。0where子句进行过滤。

于 2013-09-08T15:05:02.947 回答
2
SELECT IDGroup,Type,Category,COUNT(u.IDGroup) as NoUsers
FROM GROUPS g 
LEFT JOIN USERS u ON g.IDGroup=u.IDGroup 
WHERE IDRat=354 GROUP BY g.IDGroup 
于 2013-09-08T15:01:46.460 回答
1

选择所需的列并按 IDGroup 连接这些表和组结果

select IDGroup,Type,Category,COUNT(IDGroup) as Number_of_Users_in_this_group
FROM GROUPS JOIN USERS WHERE GROUPS .IDGroup=USERS .IDGroup 
HAVING IDRat=354 GROUP BY IDGroup
于 2013-09-08T15:06:32.333 回答