2015-03-19 57 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