sql 结果异常

使用了row_number() over(order by a) 函数进行更新结果和实际不匹配

1 )update前数据:

MySQL [test]> select a,row_number() over(order by a) bb,b from t1;
±-----±—±-----+
| a | bb | b |
±-----±—±-----+
| 0 | 1 | 2 |
| 0 | 2 | 2 |
| 0 | 3 | 2 |
| 0 | 4 | 2 |
| 0 | 5 | 2 |
| 0 | 6 | 2 |
| 0 | 7 | 2 |
| 0 | 8 | 2 |
| 0 | 9 | 2 |
| 3 | 10 | 4 |
| 3 | 11 | 4 |
| 3 | 12 | 4 |
| 3 | 13 | 4 |
| 3 | 14 | 4 |
| 3 | 15 | 4 |
| 3 | 16 | 4 |
| 3 | 17 | 4 |
| 3 | 18 | 4 |
| 3 | 19 | 4 |
| 5 | 20 | 6 |
| 5 | 21 | 6 |
| 5 | 22 | 6 |
| 5 | 23 | 6 |
| 5 | 24 | 6 |
| 5 | 25 | 6 |
| 5 | 26 | 6 |
| 5 | 27 | 6 |
| 8 | 28 | 9 |
| 8 | 29 | 9 |
±-----±—±-----+
29 rows in set (0.00 sec)

2)执行updae ,已经有条件bb>1 and bb<3,但是更新了9行,实际应该1行
MySQL [test]> update t1,(select *,row_number() over( order by a) bb from t1) tt set t1.a=1 where t1.a=tt.a and (tt.bb>1 and tt.bb<3);
Query OK, 9 rows affected (0.01 sec)
Rows matched: 9 Changed: 9 Warnings: 0

3)查询结果,应该是更新1行,实际更新9行

MySQL [test]> select a,row_number() over(order by a) bb,b from t1;
±-----±—±-----+
| a | bb | b |
±-----±—±-----+
| 1 | 1 | 2 |
| 1 | 2 | 2 |
| 1 | 3 | 2 |
| 1 | 4 | 2 |
| 1 | 5 | 2 |
| 1 | 6 | 2 |
| 1 | 7 | 2 |
| 1 | 8 | 2 |
| 1 | 9 | 2 |
| 3 | 10 | 4 |
| 3 | 11 | 4 |
| 3 | 12 | 4 |
| 3 | 13 | 4 |
| 3 | 14 | 4 |
| 3 | 15 | 4 |
| 3 | 16 | 4 |
| 3 | 17 | 4 |
| 3 | 18 | 4 |
| 3 | 19 | 4 |
| 5 | 20 | 6 |
| 5 | 21 | 6 |
| 5 | 22 | 6 |
| 5 | 23 | 6 |
| 5 | 24 | 6 |
| 5 | 25 | 6 |
| 5 | 26 | 6 |
| 5 | 27 | 6 |
| 8 | 28 | 9 |
| 8 | 29 | 9 |
±-----±—±-----+
29 rows in set (0.00 sec)

2 个赞

你这个结果是对的,因为你过滤出来tt表的数据是(0,2),但是你用a字段去匹配,这个匹配结果是多对一,t1表9条a=0的数据,所以更新9条是对的。

2 个赞

但是我有条件 (tt.bb>1 and tt.bb<3);

2 个赞

楼上说的是对的,tt表筛选之后是只有一条记录(0 2 2),但是根据条件关联t1表的时候,是匹配的t1.a和tt.a,此时tt.a的值是0,t1表中a值为0的,就是有9条记录。

2 个赞

此话题已在最后回复的 1 分钟后被自动关闭。不再允许新回复。