更新内部选择成功但数据不更新

时间:2018-05-23 09:04:39

标签: mysql

这是我的代码

UPDATE `mytable` 
SET `income` = (SELECT sum(`row`) FROM (SELECT * FROM `mytable`)AS mmc WHERE `view_date` = '2018-5-21') 
WHERE id = 1 AND view_date = '2018-5-21'

我运行此代码并且成功,但我的数据没有更新。

1 个答案:

答案 0 :(得分:0)

您可以使用以下SQL正确更新您的表。

SQL:

update mytable m
join (select id,view_date,sum(row) as row from mytable group by id,view_date) t on (m.id = t.id and m.view_date = t.view_date)
set m.income = t.row
where m.id = 1 and m.view_date = '2018-05-23';

示例如下:

mysql> create table mytable(id int,income int, row int, view_date date);
Query OK, 0 rows affected (0.54 sec)

mysql> insert into mytable values(1,null,230,current_date);
Query OK, 1 row affected (0.12 sec)

mysql> insert into mytable values(1,null,450,current_date);
Query OK, 1 row affected (0.05 sec)

mysql> select * from mytable;
+------+--------+------+------------+
| id   | income | row  | view_date  |
+------+--------+------+------------+
|    1 |   NULL |  230 | 2018-05-23 |
|    1 |   NULL |  450 | 2018-05-23 |
|    2 |   NULL |  800 | 2018-05-23 |
+------+--------+------+------------+
3 rows in set (0.00 sec)

mysql> update mytable m
    -> join (select id,view_date,sum(row) as row from mytable group by id,view_date) t on (m.id = t.id and m.view_date = t.view_date)
    -> set m.income = t.row
    -> where m.id = 1 and m.view_date = '2018-05-23';
Query OK, 2 rows affected (0.13 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from mytable;
+------+--------+------+------------+
| id   | income | row  | view_date  |
+------+--------+------+------------+
|    1 |    680 |  230 | 2018-05-23 |
|    1 |    680 |  450 | 2018-05-23 |
|    2 |   NULL |  800 | 2018-05-23 |
+------+--------+------+------------+
3 rows in set (0.00 sec)