mysql - 用一个sql更新两个不同表中的列

标签 mysql sql

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

表一

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

Table 2


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

I'm trying to update the column status in both the tables using a single sql. Actually, a moderator updates only table2 since that's the table available to him.

When table2 two gets updated, cantable1 be updated at the same time? Using a single sql? Right now, I'm using 2 different convetional sql statements for this.

Right now I do like this:

UPDATE table2 set status = 0 where id = spid and country = spcountry;//Update table2 first

        UPDATE table1 a
        INNER JOIN table2 b
        ON a.id = b.id and a.country = b.country
        SET a.status = b.status
        WHERE a.id=spid;

我希望做的事:例子

$status = 0;//php

update table1, table2 set status = $status where id=1 and conuntry = 'us' in table1 and table2.//The id and country need to be the same in both tables.

最佳答案

虽然您可以使用以下语法更新两个表

UPDATE TBL1, TBL2
SET TBL1.status = 'Blah', TBL2.status = 'blah'
WHERE TBL1.id = TBL2.id 
      AND TBL2.id = 2;

但这可能是有害的。考虑以下情况:当 TBL2 包含 id = 2 的行,而 TBL1 没有 id = 2 的行。这会导致更新失败。为了使其工作,TBL1 和 TBL2 必须完全相同。 如果这两个表完全相同,为什么一开始就没有两个表呢?


@invisal If it fails, all that'll happen is it'll say 0 rows updated, right? It wont cause the script to stop running. – jmenezes

首先,您需要确保这两个表具有相同的数据:

  • 任何插入,都需要插入到两个表中
  • 对于任何更新,您需要更新两个表
  • 删除,需要从两个表中删除

它不会阻止您的脚本运行,但您需要强制执行这些条件。如果两个表不一致,那么有时更新将不起作用。没有按预期工作的脚本和抛出错误的脚本之间没有太大区别。他们都没有做他们应该做的事。

关于mysql - 用一个sql更新两个不同表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16931552/

相关文章:

c# - EF 4.1/存储库/UnitOfWork/MySQL : There is already an open DataReader associated with this Connection which must be closed first

SQL 连接查找两个数据源之间的不一致

php - 在 MySQL 中使用 set time_zone 的问题

mysql - SQL UPDATE 语句基于另一个现有行更新列

sql - Mysql基于特定列的值转储

c# - 将 ZIP 文件插入数据库

php - 连接单个表中的两组结果

C# SQL地理 : diagnosing invalid geometries

c# - 当我从现有数据库创建模型时, Entity Framework 4.0 生成只读模型

php - 网页游戏的数据库建模