简体   繁体   English

MySQL根据另一个字段的顺序将值应用于每一行的字段

[英]MySQL apply a value a field of each row based on the order of another field

I have a table which I would like to apply a price rank for each record. 我有一张桌子,我想为每条记录应用一个价格等级。

1 for the highest, 2 for the next highest, 3 for the next highest. 1代表最高,2代表第二高,3代表第二高。

Currently I'm selecting each row and then updating each record individually like so: 目前,我正在选择每一行,然后分别更新每条记录,如下所示:

Usage: function get_list('table','order field','order direction') - returns associative array 用法:函数get_list('table','order field','order direction')-返回关联数组

foreach(get_list('ps2','price','DESC') as $p)
{
    $ct++;
    $s = "UPDATE `ps2` 
            SET `price_rank` = '".$ct."' 
            WHERE `db_id` = '".$p[db_id]."'
            LIMIT 1";
    mysql_query($s);
}

As I have many records this is extremely slow, is there another way? 由于我有很多记录,这非常慢,还有其他方法吗?

Edit: Here's one way which is way faster but is there a better way? 编辑:这是一种更快的方法,但是有更好的方法吗?

ALTER TABLE `ps2` DROP `price_rank` ;
ALTER TABLE `ps2` CHANGE `db_id` `db_id` INT( 11 ) NOT NULL ;
ALTER TABLE `ps2` DROP PRIMARY KEY ;
ALTER TABLE `ps2` ORDER BY `price_per_pax_after_tax` DESC;
ALTER TABLE `ps2` ADD `price_rank` INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
ALTER TABLE `ps2` ORDER BY `db_id`;
ALTER TABLE `ps2` CHANGE `price_rank` `price_rank` INT( 11 ) NOT NULL ;
ALTER TABLE `ps2` DROP PRIMARY KEY ;
ALTER TABLE `ps2` ADD PRIMARY KEY ( `db_id` ) ;
ALTER TABLE `ps2` CHANGE `db_id` `db_id` INT( 11 ) NOT NULL AUTO_INCREMENT ;

Personally I would handle the ranking in the DML statements using aggregate functions like MAX and limit and offset to get the results I want. 我个人将使用聚合函数(如MAX)和limit和offset来处理DML语句中的排名,以获得所需的结果。 Also when the price changes you will have to repopulate the rank values if you store them in the table. 同样,当价格变化时,如果将其存储在表中,则必须重新填充等级值。 The current methods above do not handle identical prices. 上面的当前方法无法处理相同的价格。

You can return the rank without storing it with this 您可以返回排名而不用此存储

SELECT p.db_id, COUNT(DISTINCT p2.price) as Rank 
FROM packages_sorted as p 
JOIN packages_sorted as p2 ON p.price <= p2.price 
GROUP BY p.db_id 

If you still want to store the rank, 如果您仍然想存储等级,

UPDATE FROM packages_sorted as p JOIN (
    SELECT p.db_id, COUNT(DISTINCT p2.price) as PriceRank 
    FROM packages_sorted as p 
    JOIN packages_sorted as p2 ON p.price <= p2.price 
    GROUP BY p.db_id
) as pSub ON p.db_id = pSub.db_id 
SET p.price_rank = pSub.PriceRank 

Both of those statements handle identicle prices with the count distinct. 这两个语句都以相同的数量处理相同的价格。

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

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