2013-06-04 29 views
0

我有兩個結構相同的表。其餘爲Table1,其餘爲table2MySql使用另一個表中的數據更新表

表1

 
+------+--------+---------------+--------+-----------+ 
| "id" | "name" | "description" | "type" | "country" | 
+------+--------+---------------+--------+-----------+ 
| "1" | "a" | "x"   | "1" | "US"  | 
| "2" | "b" | "x"   | "1" | "UK"  | 
+------+--------+---------------+--------+-----------+ 

表2

 
+------+-----------+-----------------+--------+-----------+----------+ 
| "id" | "name" | "description" | "type" | "country" | "status" | 
+------+-----------+-----------------+--------+-----------+----------+ 
| "1" | "Title 1" | "Description 1" | "1" | "US"  | "0"  | 
| "2" | "Title 2" | "Description 2" | "10" | "UK"  | "0"  | 
+------+-----------+-----------------+--------+-----------+----------+ 

我爲了從table 2更新table 1與數據運行以下SQL和它工作得很好。唯一的問題是,我需要在兩個地方指定id。如果我只在一個地方指定它,它會去哪裏?

UPDATE table1 dest, 
     (SELECT name, 
       description 
     FROM table2 
     WHERE id = 1) src 
SET dest.name = src.name, 
     dest.description = src.description 
WHERE dest.id = 1; 

這個事情會發生的方法是:

UPDATE table1 SET name AND description = 
(
    SELECT name, description from table2 
    WHERE id=1 AND country=us and type=10 
) WHERE id=idfromselect AND country=countryfromselect AND type=typefromselect 

我想不通的地方放idremaining conditions。你能幫我嗎?

+0

您可以使用連接條件 看到這個鏈接它可能會幫助 http://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a-id-match – learner

回答

1

將它作爲聯接,將id放入聯接條件中,並只檢查WHERE子句中的id。

事情是這樣的: -

UPDATE table1 dest INNER JOIN table2 src ON dest.id = src=id 
SET dest.name = src.name, dest.description = src.description 
WHERE dest.id=1 ; 

任何其他限制可以只被添加到WHERE子句

1

我想你可以使用一個INNER JOIN查詢來更新從表2數據的table1的築底,並把您在WHERE條款

條件
UPDATE table1 a 
INNER JOIN table2 b 
ON a.id = b.id 
SET a.name = b.name, 
a.description = b.description 
WHERE a.id=1; 
相關問題