0

我设置了两张桌子。一份用于学生信息,一份用于学生/班级列表。我正在使用 MSSQL 2008 R2 的 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'

现在我可以选择所有学生并显示所有信息;但是,我不能按姓氏对它们进行排序。我确信这是可能的,但是看到第一个查询将返回一个数组,我需要第二个查询也返回一个数组。

任何帮助将不胜感激。

4

2 回答 2

3

查看 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
于 2012-09-05T18:12:04.407 回答
1

使用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
于 2012-09-05T18:05:09.717 回答