简体   繁体   English

将MySQL查询重构为单个查询

[英]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). 如果最小不是唯一的,那么我显然会关注子集的大小-具有相等“ pop”(人气排名)的行数。 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. 就目前情况而言,由于担心重复相同的笨拙查询,我什至没有尝试确定子集中的“最旧日期”,如果该子集的大小证明大于1。

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 . 如果可能,不要mysql_*用于新代码,请转到mysqliPDO

 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. 如果有多个记录符合相同的条件,则mysql只会给您找到的第一个记录。 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. 使用WHERE或向ORDER BY子句添加更多字段。

And as mentioned before, the mysql_* functions are deprecated so you should switch to PDO or mysqli. 并且如前所述,不推荐使用mysql_*函数,因此您应该切换到PDO或mysqli。

您还可以使用子查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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