如何在具有特定属性的另一个表
table1
--------------
| sn | class |
--------------
table2
----------------
| id | student |
----------------
所有的表计算行是int
为sn
是表1是与学生在表2 sn
,id
是自动增加。插入数据表2学生列时是一样的sn
表1如何在具有特定属性的另一个表
现在我要选择在表2 student
但只有那些class
table1中是“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)
你应该加入这两个表和你的结果限制为那些具有table1.class = 3
SELECT
student
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3
如果你想有一个数,您还可以通过使用聚合函数
做到这一点通过SQLSELECT
COUNT(student)
FROM
table2 a
JOIN table1 b ON (a.student = b.sn)
WHERE b.class = 3
完美的解决方案 – Ekumahost 2014-11-06 12:30:22
您需要加入表格才能正确过滤结果。
(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'
);
在第二个和第三个示例中缺少一个报价。 – 2014-11-06 08:55:39
感谢您指出,现在修复。 – Paul 2014-11-06 08:56:10
不客气。 – 2014-11-06 08:56:32
您可以为此做一个连接,但首先让我注意您的问题是不可读的。你可以更好地编辑和重写它。 – albanx 2014-11-06 08:44:35
是否在表1中有任何类别的列 – 2014-11-06 08:48:53
如果我问的话,你不指望我的问题自己回答,那是因为我不知道。所以你可以尝试一下(从英文翻译成PHP),就像其他人一样。 – Ekumahost 2014-11-06 12:32:43