Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL ORDER BY COUNT()?

I have a table setup in my database with this structure:

table-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

like image 583
Jako Avatar asked Nov 11 '11 21:11

Jako


People also ask

Can you ORDER BY count in MySQL?

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.

Can I ORDER BY count in SQL?

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.

How do I print count in descending order in SQL?

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.

How do I count total orders in SQL?

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) .


2 Answers

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.

like image 192
Bill Karwin Avatar answered Oct 18 '22 07:10

Bill Karwin


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'");
like image 45
John Humphreys Avatar answered Oct 18 '22 08:10

John Humphreys