分别更新每一行

时间:2011-06-23 14:39:35

标签: mysql foreach row

我正在尝试更新数据库中的某些行。

我有一张如下表格:

id | subid | creation_date

1  | 1/1   | 2011-06-23

1  | 1/2   | 0000-00-00

2  | 2/1   | 2011-06-20

2  | 2/2   | 0000-00-00

我想要的是使用具有实际日期的creation_date将creation_date设置为“0000-00-00”的条目更新。

请求后的结果是:

id | subid | creation_date

1  | 1/1   | 2011-06-23

1  | 1/2   | 2011-06-23

2  | 2/1   | 2011-06-20

2  | 2/2   | 2011-06-20

有人可以帮我吗?只需要一次请求就可以实现这一点。

谢谢;)

5 个答案:

答案 0 :(得分:4)

解决另一个无法在您正在更新的子查询中拥有该表的答案的问题。让我们在临时表中创建并使用它......

CREATE TEMPORARY TABLE foo SELECT id, MAX(creation_date) FROM yo_table GROUP BY id;
UPDATE yo_table SET creation_date = ( SELECT foo.creation_date FROM foo WHERE foo.id = yo_table.id ) 
WHERE creation_date = '0000-00-00';

答案 1 :(得分:1)

update yo_table outter
set creation_date = 
    (select min(creation date) from yo_table iner where iner.id = outter.id)
where creation_date = '0000-00-00' --note that you'll have to edit this according to the data type of your creation_date column

编辑:用temp。表

create table yo_table_tmp as select * from yo_table;

    update yo_table outter
    set creation_date = 
        (select min(creation date) from yo_table_tmp iner where iner.id = outter.id)
    where creation_date = '0000-00-00' --note that you'll have to edit this according to the data type of your creation_date column
;

drop table yo_table_tmp;

答案 2 :(得分:1)

update table_a as t1, table_a as t2
set t1.creation_date=t2.creation_date
where t1.id=t2.id and (t1.creation_date=0 and t2.creation_date>0);

答案 3 :(得分:0)

创建临时表。

为了简单起见,我修改了您的subid,您可以随时将它们组合在查询结果中。

mysql> update table1 set creation_date = (SELECT x.creation_date
    from (SELECT * from table1 WHERE subid=1) AS X
    WHERE x.id =table1.id) WHERE subid=2;

Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from table1;
+----+-------+---------------+
| id | subid | creation_date |
+----+-------+---------------+
|  1 |     1 | 2011-06-23    |
|  1 |     2 | 2011-06-23    |
|  2 |     1 | 2011-06-20    |
|  2 |     2 | 2011-06-20    |
+----+-------+---------------+
4 rows in set (0.00 sec) 

答案 4 :(得分:0)

我认为这应该适合你:

UPDATE `tableA` `ta`
INNER JOIN (
    SELECT `id`, `creation_date`
    FROM `tableA`
    WHERE `creation_date` > '0000-00-00'
    GROUP BY id
) `tb` ON `ta`.`id` = `tb`.`id`
SET `ta`.`creation_date` = `tb`.`creation_date`
WHERE `ta`.`creation_date` = '0000-00-00';

希望这有帮助。