22

我的一个数据库中有一个名为“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”字段。

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

换句话说,我正在寻找这样的东西,

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

如何将递增数字分配给新引入的字段,仅用于满足给定条件的记录?

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

4

3 回答 3

59

你在寻找这样的东西吗?

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

SQLFiddle

于 2013-05-20T07:34:37.530 回答
13

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

例如::查询以更新列为空的所有行。它将通过递增 1 来更新每一行 id

    SET @a  = 50000835 ;  
    UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
    WHERE external_identifier IS NULL;
于 2015-01-14T12:46:31.120 回答
4

也许这会帮助你...

DELIMITER $$
DROP PROCEDURE IF EXISTS manual_increment_count$$
CREATE PROCEDURE manual_increment_count()
  BEGIN
    DECLARE count INT DEFAULT 0;
    DSELECT COUNT(*) INTO count FROM textile_events;
    WHILE count > 0 DO
      SET count = count + 1;
      update textile_events 
        set seq_no = count  where eid = 'headsup' AND paid = 'paid'; 
    END WHILE;
  END$$
DELIMITER ;
CALL manual_increment_count();
于 2013-05-20T07:45:47.217 回答