将行大于的所有行增加+1

时间:2015-03-19 09:02:42

标签: mysql sql-update

我有这些字段

+------------+-------------+----------------+----------+-------------+
| channel_id | channel_row | content_digest | seriesid | provider_id |
+------------+-------------+----------------+----------+-------------+
|        296 |           0 | SVT::2258207   | NULL     | NULL        |
|        296 |           1 | SVT::2354966   | NULL     | NULL        |
|        296 |           2 | SVT::2287450   | NULL     | NULL        |
|        296 |           3 | SVT::2269811   | NULL     | NULL        |
+------------+-------------+----------------+----------+-------------+

我想要做的是增加所有channel_row +1,其中channel_row is <= 1,其中1和2和3应该变为2和3和4, 0应该保持不变......

但这不起作用,至少不是我现在拥有的1个sql查询:

UPDATE channel_row SET channel_row = channel_row+1 WHERE channel_id = '296' AND channel_row <= '1' ORDER BY channel_row DESC

但必须有某种方式,对吗?或者这实际上是不可能的?

3 个答案:

答案 0 :(得分:2)

您的where语句错误:

AND channel_row <= '1' 

必须是

AND channel_row >= '1' 

答案 1 :(得分:0)

您的情况有误,<=应该是>=

UPDATE channel_row 
SET channel_row = channel_row+1 
WHERE channel_id = '296' 
AND channel_row >= '1' ORDER BY channel_row DESC

这是一个简单的测试用例

mysql> create table test (id int , val int);
Query OK, 0 rows affected (0.16 sec)

mysql> insert into test values (1,0),(1,1),(1,2),(1,3);
Query OK, 4 rows affected (0.05 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from test ;
+------+------+
| id   | val  |
+------+------+
|    1 |    0 |
|    1 |    1 |
|    1 |    2 |
|    1 |    3 |
+------+------+
4 rows in set (0.00 sec)

mysql> update test set val=val+1 where id = 1 and val > 0 ;
Query OK, 3 rows affected (0.02 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> select * from test ;
+------+------+
| id   | val  |
+------+------+
|    1 |    0 |
|    1 |    2 |
|    1 |    3 |
|    1 |    4 |
+------+------+
4 rows in set (0.00 sec)

答案 2 :(得分:0)

您的<=不正确。您想更新所有较高的0,因此必须channel_row > 0。该号码也不应该在''

UPDATE table_name 
SET channel_row = channel_row + 1 
WHERE channel_id = 296 AND channel_row > 0

不需要ORDER BY语句