对 MySQL 数据库中的列值进行排名 [英] Ranking column values in a MySQL database

查看:92
本文介绍了对 MySQL 数据库中的列值进行排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对我的数据库中的值进行排名练习.每列是一年,每列有 76 个值(即每年下 76 行).年份是从1980年到2035年.我的脚本必须依次遍历每一年(列),并对值进行排序(即按升序排列然后吐出关联的ID).

I am performing a ranking exercise for values in my database. Each column is a year and each has 76 values (i.e. 76 rows under each year). The years are from 1980 to 2035. My script must go through each year (column) in turn, and rank the values (i.e. arrange them in ascending order and then spit out the associated IDs).

我写了下面的脚本,它可以工作,但需要三秒钟,我认为这很慢.对于第一列 (1980),它很快,因为我可以一次性插入它们.对于其他人,我不能,因为我需要更新表并因此匹配行 - 这会导致每个值的单独 SQL 查询.

I have written the script below, and it works, but it takes three seconds which I think is very slow. For the first column (1980) it's quick, as I can insert them in one go. For the others I cannot as I need to UPDATE the table and therefore match rows - which results in a separate SQL query for each value.

有没有更好的方法来做到这一点?这是我的代码:

Is there a better way to do this? Here is my code:

for ($x = 1980; $x <= 2035; $x++) {
    $sql="SELECT `ID`,`$x` FROM marginal_costs ORDER BY `$x`";
    $concat = "";
    $counter = 1;
    $result = mysqli_query($con,$sql);

    while($row = mysqli_fetch_array($result)) {
        if($x==1980) {
             $concat = $concat."('".$row['ID']."'), ";
        } else {   
             $upload="UPDATE `merit_order` SET `$x`='".$row['ID']."' WHERE `ID`='$counter';";
             echo $upload;
             mysqli_query($con, $upload);
             $counter= $counter + 1; 
        }
    }

    if($x==1980) {
        $concat = substr_replace($concat, "", -2).";";
        $upload="INSERT INTO `merit_order` (`$x`) VALUES $concat;";
        mysqli_query($con, $upload);
    }
}

推荐答案

您的代码向您的数据库发送了大量 SQL,从而产生了不必要的通信.这是您可以优化的一件事...两个选项:

Your code sends a lot of SQLs to your database generating unnecessary communication. This is one thing you could optimize... Two options:

  • 你编写了一个存储过程来完成这一切,所以你优化了一点通信,但你给了你的数据库一些额外的工作;
  • 尽量减少您使用的 SQL 数量:尝试获取一次数据(您构建一个大选择,您可以选择所有内容,所有年份);在php中做排名;然后构造一些更新(例如为每个 id)和插入,并将它们发送到数据库;你就完成了:)

这篇关于对 MySQL 数据库中的列值进行排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆