我设置了两个表。一个用于学生信息,一个用于列出学生/班级。我正在使用MSSQL2008R2的sqlsrv插件用PHP进行编码。
Student ID
Class Code
Student ID
First Name
Last Name
我需要从一个班级中选出所有的学生,但要按姓氏排序。
SELECT student_id FROM table1 WHERE class_code LIKE '402843'
$students = SELECT last_name, first_name FROM table2 WHERE student_id LIKE 'all results of first query'
现在我可以选择所有的学生并显示所有的信息;但是,我不能按姓氏对它们进行排序。我确信这是可能的,但鉴于第一个查询将返回一个数组,我需要第二个查询也返回一个阵列。
如有任何帮助,我们将不胜感激。
查看SQL中的联接,并在查询中而不是在PHP中完成所有联接。。。
使用您的示例并出于代码的目的,将表命名为
ClassCodeTable
Student ID
Class Code
StudentInfoTable
Student ID
First Name
Last Name
那么您的查询看起来像
SELECT SI.last_name, SI.first_name FROM StudentInfoTable SI JOIN ClassCodeTable CC on CC.student_id=SI.student_id WHERE CC.class_code LIKE '402843' ORDER BY SI.last_name ASC
使用IN
子查询:
SELECT last_name, first_name FROM table2 WHERE student_id IN (SELECT student_id FROM table1 WHERE class_code='402843') ORDER BY last_name ASC