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

标签 mysql sql sql-update

我有两个结构相同的表。 Table1 保存经过审核的数据,table2 保存其余数据。

表1

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

Table 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. The only problem is, I need to specify the id in both places. 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; 

事情的发展方式是:

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剩余条件放在哪里。你能帮忙吗?

最佳答案

将其作为联接进行,将 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 子句中

关于MySql 使用另一个表中的数据更新一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16916685/

相关文章:

php - 当我使用外部 php 文件执行所有类型的查询时,如何获取 INSERT 查询的最后一个 id?

java - 在 h2 数据库中编写查询以转换日期格式

MYSQL - 将日期从 2020 年更改为 2011 年

php - 在php中动态创建新变量

php - 在mysql中更新表得到奇怪的结果

mysql - Laravel5 : SQLSTATE[42000]: Syntax error or access violation: 1055

php - SQL注入(inject)-通过URL访问

sql - WiX:你如何更新数据库?

sql - 触发更新不同的表

mysql - 我应该在 MySQL 表中放置索引