简体   繁体   English

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

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

I have two tables that are identical in structure. 我有两个结构相同的表。 Table1 holds moderated data, table2 holds the rest. Table1保存调节数据, table2保存其余数据。

Table 1 表格1

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

Table 2 表2

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

I run the below sql in order to update table 1 with data from table 2 , and it works well. 我运行下面的sql以使用table 2数据更新table 1 ,并且它运行良好。 The only problem is, I need to specify the id in both places. 唯一的问题是,我需要在两个地方指定id If I were to specify it only in one place, where would it go? 如果我只在一个地方指定它,它会去哪里?

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; 

The way this thing goes is: 这件事的方式是:

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

I can't figure out where to put the id and remaining conditions . 我无法弄清楚在哪里放置idremaining conditions Can you help? 你能帮我吗?

Do it as a join, put the id in the join condition and just check the id in the WHERE clause. 将它作为连接,将id放在连接条件中,然后检查WHERE子句中的id。

Something like this:- 像这样: -

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 ;

Any other restrictions can just be added to the WHERE clause 可以将任何其他限制添加到WHERE子句中

I think you can use an INNER JOIN query to update your table1 basing on data from table2 and put your condition in WHERE clauses 我认为您可以使用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