2011-06-23 49 views
2

我試圖更新我的數據庫中的一些行。分別更新每一行

我有這樣一個表如下:

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設置項爲「0000-00-00」與誰擁有一個真正的日期之一CREATION_DATE 。

請求後,其結果將是:

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 

有人在那裏可以有一個想法,以幫助我嗎?伊爾將竭盡全力,以一個單一的要求。

感謝)

B.

回答

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 

編輯:用溫度。表

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

@Gidon爲什麼最小或最大的問題?任何一個根據發佈的信息OP工作。 – Jordan

+0

嗯,似乎與此查詢,我有一個錯誤:「你不能指定目標表'outter'在FROM子句更新」 – LostInSql

+0

@LostInSql,你是對的,我忘了1093.你需要一個臨時表,看我的編輯。 – bpgergo

3

解決與其他答案無法在您正在更新的子查詢中有表的問題。就讓我們在創建臨時表和使用......

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'; 
+0

在表創建MAX(creation_date)之後添加「as mcd」並修改foo.mcb 感謝;) – LostInSql

+0

oops關於「as」的好處!但不要忘記在哪裏 –

+0

很好,+1分 – bpgergo

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); 
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) 
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'; 

希望這有助於。