MySQL:迭代和更新表中的记录

时间:2014-01-27 17:24:41

标签: mysql stored-procedures

我有一张包含以下记录的表格:

USER  | STATUS
--------------
user1 | 1
user2 | 1
user1 | 1
user2 | 1
user1 | 0
user2 | 1
user3 | 1

我想添加一个字段COUNT并更新表格,以便COUNT的值如下所示:

USER  | STATUS | COUNT
----------------------
user1 | 1      | 1
user2 | 1      | 1
user1 | 1      | 2
user2 | 1      | 2
user1 | 0      | NULL # Don't want to update where STATUS=0
user2 | 1      | 3
user3 | 1      | 1

我对Stored Procedures知之甚少,而我试过的那些并没有真正提供我想要的输出。

非常感谢有人可以帮助我。谢谢!

3 个答案:

答案 0 :(得分:2)

无需存储过程。我添加了一个auto_increment列,否则它将是不确定的。

示例数据:

CREATE TABLE t
    (id int auto_increment primary key, `USER` varchar(5), `STATUS` int)
;

INSERT INTO t
    (`USER`, `STATUS`)
VALUES
    ('user1', 1),
    ('user2', 1),
    ('user1', 1),
    ('user2', 1),
    ('user1', 0),
    ('user2', 1),
    ('user3', 1)
;

ALTER TABLE t ADD COLUMN COUNT int default null;

查询:

UPDATE t
INNER JOIN (
  SELECT
  id,
`USER`, `STATUS`,
CASE WHEN (@my_count := IF(@prevUser != USER, 1, @my_count + 1)) IS NULL THEN NULL
WHEN (@prevUser := USER) IS NULL THEN NULL
ELSE @my_count END AS `COUNT`
FROM
t,
(SELECT @my_count := 0, @prevUser := NULL) init
WHERE
STATUS != 0
ORDER BY USER, id
  ) sq ON sq.id = t.id
SET t.COUNT = sq.COUNT;

结果:

| ID |  USER | STATUS |  COUNT |
|----|-------|--------|--------|
|  1 | user1 |      1 |      1 |
|  2 | user2 |      1 |      1 |
|  3 | user1 |      1 |      2 |
|  4 | user2 |      1 |      2 |
|  5 | user1 |      0 | (null) |
|  6 | user2 |      1 |      3 |
|  7 | user3 |      1 |      1 |

答案 1 :(得分:1)

如果你有一个id列,你可以使用下面的查询(你必须添加一个名为prevUser的列,然后你可以删除该列)

ALTER TABLE users ADD COLUMN prevUser varchar(50);
SET @prevUser = '';
SET @count = 0;
UPDATE users 
SET count = (@count:=IF(@prevUser != user,1,@count+1)),
    prevUser = (@prevUser := user)
WHERE status != 0
ORDER BY user,id;
ALTER TABLE users DROP COLUMN prevUser;

sqlFiddle

答案 2 :(得分:0)

不使用会话变量的版本

ALTER TABLE users ADD COLUMN `count` INT;

UPDATE users u JOIN 
(
  SELECT id,
  (
    SELECT 1 + COUNT(*) 
      FROM users
     WHERE user = t.user
       AND id < t.id
  ) count
    FROM users t
   WHERE status = 1
) q
    ON u.id = q.id
   SET u.count = q.count

结果:

| ID |  USER | STATUS |  COUNT |
|----|-------|--------|--------|
|  1 | user1 |      1 |      1 |
|  2 | user2 |      1 |      1 |
|  3 | user1 |      1 |      2 |
|  4 | user2 |      1 |      2 |
|  5 | user1 |      0 | (null) |
|  6 | user2 |      1 |      3 |
|  7 | user3 |      1 |      1 |

这是 SQLFiddle 演示