MySQL使用递增变量更新字段

时间:2013-05-20 07:24:42

标签: mysql mysqli

我的一个数据库中有一个名为'textile_events'的表。

mysql> describe textile_events;

+-------------+--------------+-----+---------+----------------+
| Field       | Type         | Key | Default | Extra          |
+-------------+--------------+-----+---------+----------------+
| id          | int(11)      | PRI | NULL    | auto_increment |
| token       | varchar(20)  |     | NULL    |                |
| reg_time    | datetime     |     | NULL    |                |
| eid         | varchar(20)  |     | NULL    |                |
| fname       | varchar(20)  |     | NULL    |                |
| lname       | varchar(20)  |     | NULL    |                |
| paid        | varchar(10)  |     | NULL    |                |
| seq_no      | int(11)      |     | NULL    |                |
+-------------+--------------+-----+---------+----------------+
8 rows in set (0.00 sec)

mysql> select count(*) from textile_events;

+----------+
| count(*) |
+----------+
|     9325 |
+----------+
1 row in set (0.00 sec)

mysql> select count(*) from textile_events where eid = 'headsup' ;

+----------+
| count(*) |
+----------+
|     2553 |
+----------+
1 row in set (0.01 sec)

'seq_no'字段昨天被引入上表。

现在,我需要为'seq_no'字段为所有'headup'分配一个递增的数字 付费字段等于“付费”的事件。

换句话说,我正在寻找类似的东西,

$i = 250
while( true ):
    $i++
    UPDATE textile_events SET 'seq_no' = $i 
        WHERE eid = 'headsup' AND paid = 'paid'
endwhile;

如何为新引入的字段分配递增数字,仅用于重新计算 是否满足某一特定条件?

有哪些可用选项以及实现此目标的最有效方法是什么?

3 个答案:

答案 0 :(得分:45)

你在找这样的东西吗?

UPDATE textile_events e,
       (SELECT @n := 249) m
   SET e.seq_no = @n := @n + 1 
    WHERE e.eid = 'headsup' AND e.paid = 'paid'

<强> SQLFiddle

答案 1 :(得分:8)

简单查询就是,只需将变量设置为您想要的某个数字。然后通过从该数字递增1来更新所需的列。

Ex :: Query更新列为空的所有行。它会通过递增1

来更新每个行ID
    SET @a  = 50000835 ;  
    UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
    WHERE external_identifier IS NULL;

希望这对某人有所帮助。 :)

答案 2 :(得分:4)

可能这会对你有帮助......

DELIMITER $$
    DROP PROCEDURE IF EXISTS manual_increment_count$$
    CREATE PROCEDURE manual_increment_count()
    BEGIN
     DECLARE count INT DEFAULT 0;
     SELECT COUNT(*) INTO count FROM textile_events 
     WHILE count > 0 
       SET count = count + 1;
       update textile_events 
            set seq_no = count  where eid = 'headsup' AND paid = 'paid'; 
     END WHILE;
    END$$
    DELIMITER ;