简体   繁体   中英

How do I combine multiple queries into an array?

I have two tables set up. One for student information, one for student/class listing. I'm coding in PHP using the sqlsrv plugin for MSSQL 2008 R2.

Student ID
Class Code

Student ID
First Name
Last Name

I need to select all students from a class but order by 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'

Right now I can select all the students and display all the information; however, I can not sort them by last name. I'm sure this is possible, but seeing that the first query will return an array, I need the second query to return an array as well.

Any help would be greatly appreciated.

look at joins in SQL and do it all in your query rather than in PHP...

using your examples and for the purposes of code, naming the tables as follows

ClassCodeTable  
    Student ID
    Class Code

StudentInfoTable
    Student ID
    First Name
    Last Name

then your query would look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM