选择相同表的mysql更新

时间:2015-02-04 12:14:18

标签: mysql select updates

我要更新表事务

CREATE TABLE `transaction` (
  `id` int(11) NOT NULL auto_increment,
  `amount` decimal(15,2) NOT NULL default '0.00',
  `rate` decimal(9,7) NOT NULL default '0.0000000',
  `amount1` decimal(15,2) NOT NULL default '0.00',
  `date_time` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=4 ;


INSERT INTO `transaction` (`id`, `amount`, `rate`, `amount1`, `date_time`) VALUES
(1, 100.00, 0.8000000, 80.00, '2015-02-03 16:56:58'),
(2, 100.00, 0.7820000, 78.20, '2015-02-04 01:45:24');

我的最终结果需要是:

(1, 100.00, 0.7600000, 76.00, '2015-02-03 16:56:58'),
(2, 100.00, 0.7429000, 74.29, '2015-02-04 01:45:24');

我尝试使用此查询更新列速率

从交易中选择费率* 0,95

但是

update transaction set rate = (select rate *0,95 from transaction where <Date_time_condition>) where <Date_time_condition>

不行 在此更改之后,amount1 = amount * rate

3 个答案:

答案 0 :(得分:1)

试试这个,

update transaction set rate = rate * 0.95 where <Datetime condition>

答案 1 :(得分:0)

假设条件与外部表没有关联,那么您可以将子查询移动到join子句:

update transaction t cross join
       (select rate *0,95 as newrate from transaction where <Date_time_condition>) val
    set t.rate = val.newrate
    where <Date_time_condition>;

但是,您可能根本不需要子查询。也许这就是你想要的:

update transaction t
    set t.rate = 0.95 * t.rate
    where <Date_time_condition>;

答案 2 :(得分:0)

update transaction set rate = (select (rate *0.95) as result 
from transaction where <Date_time_condition>) where <Date_time_condition>