[英]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.