[英]MySQL COUNT with GROUP AND JOIN
I need help to SELECT some information from 3 tables with one SQL query. 我需要一个SQL查询来从3个表中选择一些信息的帮助。 I will try to explain it as much as possible.
我会尽力解释。
I have the following 3 tables: 我有以下3表:
ID | FULL NAME | CATEGORY_ID
--------------------------
1 | JOHN DOE | 3
2 | JOHN DOE | 5
3 | JOHN DOE | 2
4 | JOHN DOE | 3
5 | JOHN DOE | 3
ID | NAME
----------------------
2 | CATEGORY NAME 1
3 | CATEGORY NAME 2
5 | CATEGORY NAME 3
ID | USER_ID
------------
1 | 1
2 | 2
3 | 4
Now I want the outcome of this SQL query to be an html table looking like: 现在,我希望此SQL查询的结果是一个如下所示的html表:
Category | 分类 | Number Of Registrations
注册数量
CATEGORY NAME 2 | 类别名称2 | 3
3
CATEGORY NAME 3 | 类别名称3 | 3
3
CATEGORY NAME 1 | 类别名称1 | 1
1
So to sum it up, I have to select all user_id
from registrations
table, get the category_id
for each user from users
table and find the category name
from categories
table. 综上所述,我必须从
registrations
中选择所有user_id
,从users
表category_id
获取每个用户的category_id
,然后从categories
表中找到类别name
。
Is this doable? 这可行吗?
The SQL tables form you're using doesn't feel right. 您正在使用的SQL表形式感觉不正确。
You should have a 'USERS' table as: 您应该具有一个“ USERS”表,如下所示:
ID | FULL NAME
1 | JOHN DOE
2 | JOHN DOE
3 | JOHN DOE
4 | JOHN DOE
5 | JOHN DOE
'CATEGORIES' table as “类别”表为
ID | NAME
2 | CATEGORY NAME 1
3 | CATEGORY NAME 2
5 | CATEGORY NAME 3
'REGISTRATIONS' table as (I believe this table will store what user has registered to what category) “ REGISTRATIONS”表为(我相信该表将存储用户已注册的类别)
USER_ID | CATEGORY_ID
1 | 1
2 | 2
3 | 4
Then your query can be easily retrieved via: 然后可以通过以下方式轻松检索查询:
SELECT c.name, count(*) as Number_of_Registrations
FROM categories c, registrations r
WHERE c.id = r.category_id
GROUP BY c.id;
Am I wrong about the registrations table? 我对注册表有错吗? Lemme know then, I'll provide a new solution accordingly.
然后Lemme知道,我将相应地提供一个新的解决方案。
I think this should do it: 我认为应该这样做:
select cat.`category name`, count(reg.user_id) from registrations reg
inner join users on reg.user_id = users.ID
inner join categories cat on cat.ID = users.category_id
group by cat.category_id
You can try this 你可以试试这个
SELECT c.name, count(r.user_id)
FROM categories c
inner join users u
on u.category_id = c.id
inner join registrations r
on r.user_id = u.id
group by c.id
$sql1="SELECT * FROM CATEGORIES"; $query1=mysqli_query($con,$sql1); echo "<table>"; while($row1=mysqli_fetch_assoc($query1)){ echo"<tr><td>". $row1['NAME']."</td >"; $sql12="SELECT COUNT(CATEGORY_ID) AS NumberOfUsers FROM USERS WHERE CATEGORY_ID='".$row1['CATEGORY_ID']."'"; $query2=mysqli_query($con,$sql12); $row2=mysqli_fetch_assoc($query2); echo"<td>".$row2['NumberOfUsers']."</td></tr>" ; } echo"</table>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.