[英]how to count rows in table that has specific property in another table
table1
--------------
| sn | class |
--------------
table2
----------------
| id | student |
----------------
因为sn
是table1,所以所有都是int
,而table2中的sn
链接到了学生sn
, id
会自动增加。 将数据插入到table2学生列中时与表1中的sn
相同
现在我想在表2中选择student
,但是只有那些在表1中的class
是“ 3”的学生,我的语法才是;
$count = mysql_query(SELECT student from table2 whose class in table1 =3)
这样我就可以说
$quantity = mysql_num_rows($count)
现在我的问题是,如果sql也具有此关键字,或者我该如何处理。
$count = mysql_query(SELECT student from table2 whose class in table1 =3)
您需要连接表才能正确过滤结果。
(1)这将为您提供3年级的学生人数。
$count = mysql_query(
'SELECT COUNT(t2.student)
FROM table2 t2
INNER JOIN table1 t1
ON t1.sn = t2.student
AND t1.class = 3'
);
(2)这将为您提供所有课程以及每个课程的学生人数。
$count = mysql_query(
'SELECT t1.class, COUNT(t2.student)
FROM table2 t2
INNER JOIN table1 t1
ON t1.sn = t2.student
GROUP BY t1.class
ORDER BY t1.class'
);
(3)这将为您提供所有班级和学生名单。
$list = mysql_query(
'SELECT t1.class, GROUP_CONCAT(t2.student SEPARATOR ',')
FROM table2 t2
INNER JOIN table1 t1
ON t1.sn = t2.student
GROUP BY t1.class
ORDER BY t1.class'
);
您应该将这两个表连接起来,并将结果限制为具有table1.class = 3的那些表
SELECT
student
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3
如果要计数,也可以使用聚合函数通过SQL进行计数
SELECT
COUNT(student)
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.