[英]how to count rows in table that has specific property in another table
table1
--------------
| sn | class |
--------------
table2
----------------
| id | student |
----------------
all are int
as sn
is table1 is linked to student in table2 sn
, id
are auto increasing. 因为sn
是table1,所以所有都是int
,而table2中的sn
链接到了学生sn
, id
会自动增加。 when inserting data to table2 student column is same as sn
in table 1 将数据插入到table2学生列中时与表1中的sn
相同
now I want to select student
in table2 but only those whose class
in table1 is "3" my syntax is thus; 现在我想在表2中选择student
,但是只有那些在表1中的class
是“ 3”的学生,我的语法才是;
$count = mysql_query(SELECT student from table2 whose class in table1 =3)
so that i can count them by saying 这样我就可以说
$quantity = mysql_num_rows($count)
now my problem is if sql also have this whose keyword, or how do i go about this. 现在我的问题是,如果sql也具有此关键字,或者我该如何处理。
$count = mysql_query(SELECT student from table2 whose class in table1 =3)
You need to join the tables in order to filter the results properly. 您需要连接表才能正确过滤结果。
(1) This will give you the number of students for class 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) This will give you all classes and the number of students for each. (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) This will give you all classes and the students list. (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'
);
You should join those two tables and limit your result to those which have table1.class = 3 您应该将这两个表连接起来,并将结果限制为具有table1.class = 3的那些表
SELECT
student
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3
If you want a count you could also do it through SQL by using aggregate function 如果要计数,也可以使用聚合函数通过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.