2015-03-19 54 views
0

我有这些领域增量所有+1行其中一行大于

+------------+-------------+----------------+----------+-------------+ 
| 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 

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

+0

它不应该是> = 1? – 2015-03-19 09:04:32

回答

2

你在那里说法是错误的:

AND channel_row <= '1' 

必须

AND channel_row >= '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) 
0

您的<=是不正确的。你想更新所有更高的0,所以它必须是channel_row > 0。另外,数量不宜在''

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

ORDER BY声明不需要

+0

哦......太容易了......非常感谢你! – DreamHawk 2015-03-19 09:12:35

+0

似乎我需要“ORDER BY”,因为如果没有它,我会得到“错误代码:1062.关键'PRIMARY'的重复条目'296-3'”,如果我使用ORDER BY,我不明白。 – DreamHawk 2015-03-19 09:19:05

+0

好的,我编辑解决方案。你必须把表名称放在'UPDATE'后面。也许你不需要'ORDER BY'语句 – Zer0x 2015-03-19 09:25:05