繁体   English   中英

MySql使用另一个表中的数据更新表

[英]MySql Update a table with data from another table

我有两个结构相同的表。 Table1保存调节数据, table2保存其余数据。

表格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"      |
+------+-----------+-----------------+--------+-----------+----------+

我运行下面的sql以使用table 2数据更新table 1 ,并且它运行良好。 唯一的问题是,我需要在两个地方指定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 你能帮我吗?

将它作为连接,将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子句中

我认为您可以使用INNER JOIN查询根据table2中的数据更新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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM