【问题标题】:Replacing a table if another table exists如果另一个表存在则替换一个表
【发布时间】:2021-11-12 05:24:33
【问题描述】:

我有 2 个 MySQL 表:

  1. 'table_a'
  2. “table_b”包含“table_a”的更新内容。

我希望“table_b”替换“table_a”并被称为“table_a”,但前提是“table_b”存在。否则,什么都不做。

我尝试使用DROP TABLE IF EXISTS table_aRENAME TABLE table_b TO table_a 的组合但没有任何成功。

这是正确的方法吗?

【问题讨论】:

标签: mysql


【解决方案1】:

我认为最简单的解决方案是:

rename table table_a to table_old, table_b to table_a;

并捕获错误。如果table_b 不存在,则不会执行任何重命名。

如果成功,您需要删除 table_old 否则它仍然存在:

MariaDB [test]> show tables
    -> ;
+----------------+
| Tables_in_test |
+----------------+
| table_a        |
| table_b        |
+----------------+
2 rows in set (0.001 sec)

MariaDB [test]> rename table table_a to table_old, table_b to table_a;
Query OK, 0 rows affected (0.004 sec)

MariaDB [test]> drop table table_old;
Query OK, 0 rows affected (0.002 sec)

MariaDB [test]> rename table table_a to table_old, table_b to table_a;
ERROR 1146 (42S02): Table 'test.table_b' doesn't exist

MariaDB [test]> show tables;
+----------------+
| Tables_in_test |
+----------------+
| table_a        |
+----------------+
1 row in set (0.001 sec)

【讨论】:

  • 我喜欢简单,发现错误总是比预测错误更容易。
猜你喜欢
  • 2016-01-19
  • 2023-01-31
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 2018-03-09
相关资源
最近更新 更多