Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Subqueries

Status
Not open for further replies.
Jan 20, 2005
65
GB
My host provider is running MySQL 4.0.24.

I have this query

SELECT `hbsclasses`.`classID`,
`hbsclasses`.`className`,
COUNT(`hbscompanies`.`classID`) AS Totals
FROM `hbscompanies`,
`hbsclasses`
WHERE `hbscompanies`.`classID` = `hbsclasses`.`classID` GROUP BY `hbscompanies`.`classID`
ORDER BY Totals DESC LIMIT 0,25";

I need the results of this query to be sorted alphabetically on `hbsclasses`.`className`.
 
Anything in the SELECT clause or the ORDER BY clause must be in the GROUP BY clause. Think of the GROUP BY as defining a new table; the columns used to group things are the columns available to display in the SELECT list or to sort by in the ORDER BY list.

So you may have a little problem if a company can have many classes; but not if it is the class which has many companies.

In the latter case, change the query to GROUP BY `hbsclasses`.`classID`.
And since there will be one className for each classID, you can group on both columns. So-
Code:
SELECT `hbsclasses`.`classID`, 
       `hbsclasses`.`className`, 
        COUNT(`hbscompanies`.`classID`) AS Totals 
FROM `hbscompanies`, 
     `hbsclasses`
WHERE `hbscompanies`.`classID` = `hbsclasses`.`classID`
GROUP BY ``hbsclasses`.`classID`, `hbsclasses`.`className` 
ORDER BY Thbsclasses`.`className DESC LIMIT 0,25";

Since there will be one Totals for each class you must decide to ORDER BY one or the other, you cant have it both ways.

I have never seen those backward apostrophes in SQL before. What do they mean?

Perhaps, I answered the wrong question. Let me know.
 
Thanks rac2,

I'm using the order by and limit to find the top 25 classes. I don't know if this can be done any better (but it works).

r937 is correct, the back ticks are used by phpMyAdmin.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top