在mysql中创建查询的问题

时间:2013-09-08 14:57:57

标签: php mysql sql database

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

组:

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

IDGroup是主键。

USERS:

| 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                             |

3 个答案:

答案 0 :(得分: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子句进行过滤。

答案 1 :(得分: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 

答案 2 :(得分: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