Alicia Posted October 9, 2012 Share Posted October 9, 2012 hi guys, can somebody give me an idea how I sort the records that I want to display order by value that I sum up from records? I have a query like this : // in a while loop $sold = mysql_query("SELECT COUNT( class ) AS num FROM `Student` WHERE class ='xxx' "); Anyway I can do something in a new query like select * from class order by num ASC ? first i want to count how many students in every class from Student table then I want to arrange the class records and display in a web page order by number of students they have in each of the classes. I am not able to sort from the class table because there is no column for this value, thats why I need to count from another table first. TQ Quote Link to comment https://forums.phpfreaks.com/topic/269258-sorting-records/ Share on other sites More sharing options...
ManiacDan Posted October 9, 2012 Share Posted October 9, 2012 SELECT class, COUNT(0) AS num FROM Student GROUP BY class ORDER BY count(0) ASC Quote Link to comment https://forums.phpfreaks.com/topic/269258-sorting-records/#findComment-1383948 Share on other sites More sharing options...
mikosiko Posted October 9, 2012 Share Posted October 9, 2012 I'm guessing that you finally need the information from the "class" table, is that is true only one query using a JOIN between "class" and "students" should be enough SELECT class.*, count(students.class) AS ngroup // if you don't need ALL the columns of the guess table don't use "*" and name the columns that you need FROM class LEFT JOIN students ON students.class = class.id // assuming that "class.id" is the same column as students.class. GROUP BY class.id // assuming that "id" is your class table PK ORDER BY ngroup ASC Quote Link to comment https://forums.phpfreaks.com/topic/269258-sorting-records/#findComment-1383954 Share on other sites More sharing options...
ManiacDan Posted October 9, 2012 Share Posted October 9, 2012 Ah, didn't see your table name had changed. Mikosiko is right. Quote Link to comment https://forums.phpfreaks.com/topic/269258-sorting-records/#findComment-1383965 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.