简体   繁体   中英

Refactoring MySQL queries to a single query

Is there a nice way of doing this.

Basically i have a hundred rows and i am ordering in ascending order to find the least popular. If the least is not unique i am concerned with obviously the size of the subset - number of rows with equal "pop" (popularity ranking). In order to determine the size of this subset i have the following code.

However, being a novice ,i am conscious that it seems a little clumsy.

$leastpop = mysql_query(" SELECT * FROM homepage ORDER BY pop ASC   LIMIT 1 ");

$pop = mysql_fetch_array($leastpop); 

$check = mysql_query("SELECT * FROM homepage WHERE pop = '$pop'");  

$count = mysql_num_rows($check);

if($count>=1)
{
//find the element with the corresponding "oldest date"



}

As it stands i have not even attempted to determine the "oldest date" among the subset should the size of this subset prove to be greater than one for fear of repeating the same clumsy queries.

Is there a better and more efficient way of approaching this problem? I hope i have been clear enough. Cheers.

maybe trying a query along these lines will help:

select pop, count(*), min(date_field) from homepage group by pop order by pop ASC limit 1;

This will give you the least popular pop, with the count of rows for that pop and the oldest date (minimum date). These functions are called aggregation functions, because they do just that.

Don't use mysql_* anymore for new code if possible, go mysqli or PDO .

 SELECT h1.* FROM homepage h1
 LEFT JOIN homepage h2
 ON h2.pop <= h1.pop AND h2.date_column <= h1.date_column
 WHERE h2.id IS NULL;

Assuming that you want the least popular with the oldest date, you just need one (simple...) query:

SELECT * FROM homepage ORDER BY pop, insert_date LIMIT 1

If there are multiple records that match the same criteria, mysql will just give you the first one it finds. If that is not specific enough, you would have to add more criteria; either using WHERE or by adding more fields to the ORDER BY clause.

And as mentioned before, the mysql_* functions are deprecated so you should switch to PDO or mysqli.

您还可以使用子查询:

$check = mysql_query("SELECT * FROM homepage WHERE pop IN (SELECT h2.pop FROM homepage AS h2 ORDER BY h2.pop ASC LIMIT 1)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM