I have a table setup in my database with this structure:
I have running a query through a while loop and I want to order by the count of the prof column.
This is what my query currently looks like, though I keep getting errors.
$order_list = mysql_query("
SELECT COUNT(prof),
FROM prof_rating
ORDER BY COUNT(prof) ASC");
This is the warning I keep getting.
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in
Use ORDER BY with DESC to order in descending order. For counting the values, use the COUNT(). For example, if the name “John” appears thrice in the column, then a separate column will display the count 3 and in this way all the count values will be arranged in descending order using the ORDER BY DESC.
ORDER BY COUNT clause in standard query language(SQL) is used to sort the result set produced by a SELECT query in an ascending or descending order based on values obtained from a COUNT function. For uninitiated, a COUNT() function is used to find the total number of records in the result set.
The ORDER BY command is used to sort the result set in ascending or descending order. The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.
The first step is to use the GROUP BY clause to create the groups (in our example, we group by the country column). Then, in the ORDER BY clause, you use the aggregate function COUNT, which counts the number of values in the column of your choice; in our example, we count distinct IDs with COUNT(id) .
For what it's worth, any use of an aggregate function in the select-list means that the result set will have only one row. It makes little sense to sort a results set with a single row.
If you meant to get a count of ratings per distinct value of prof, you should use this:
$order_list = mysql_query("
SELECT prof, COUNT(*) AS PROFCOUNT,
FROM prof_rating
GROUP BY prof
ORDER BY PROFCOUNT ASC'");
That will output multiple rows, one row per prof value, with the count of rows for each given prof value.
Alias the column name and then put that in your order by clause :)
$order_list = mysql_query("
SELECT COUNT(prof) AS PROFCOUNT,
FROM prof_rating
ORDER BY PROFCOUNT ASC'");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With