real_illusions Posted May 9, 2011 Share Posted May 9, 2011 Hi,Would like some advice on the best way to achieve this.I have a bunch of data in the database, a number associated with a set name (out of a few choices).Now, for each name, I need to display the top 2 numbers (the 2 highest numbers).I could do a select statement for each name, but then that'll involve several calls to the database, which while it isn't the greatest sin in the world, its not exactly the greatest way of coding.I've been thinking of getting all the data, and making an array, and then for each name, sort the array by the 2 highest number.Does that make any sense? Link to comment Share on other sites More sharing options...
thescientist Posted May 9, 2011 Share Posted May 9, 2011 you could SELECT * from the database, ORDER BY the column with the numbers, have it be DESC, and then LIMIT 2 to cap the results to only the 2 highest scores.http://www.w3schools.com/sql/sql_orderby.asp Link to comment Share on other sites More sharing options...
Skemcin Posted May 9, 2011 Share Posted May 9, 2011 Its going to be a little more complicated that what is offered by thescientist - I think.You could try a subquery but I think you'll run into limitation on the WHERE or ORDER BY clauses. In a stored procedure, you could use a combination of queries and temp tables to the results you're looking for. Link to comment Share on other sites More sharing options...
real_illusions Posted May 10, 2011 Author Share Posted May 10, 2011 Thanks, have figured out a solution.Its not too elegant as it does call the database a few times via the select statement to different tables, but it does the trick and seems to be the easiest to display whats needed. Link to comment Share on other sites More sharing options...
Synook Posted May 11, 2011 Share Posted May 11, 2011 You can't LIMIT within a subquery correlated through an IN clause, which makes it a lot more difficult to achieve within a single query. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.