我有兩個結構相同的表。其餘爲Table1
,其餘爲table2
。MySql使用另一個表中的數據更新表
表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
我想不通的地方放id
和remaining conditions
。你能幫我嗎?
您可以使用連接條件 看到這個鏈接它可能會幫助 http://stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a-id-match – learner