mysql - 创建一个表,其名称必须是另一个表中的主键

标签 mysql

有没有一种方法可以强制我的 MySQL 数据库允许创建名为 table_xyz 的新表,前提是另一个表中存在带有 table_xyz 的记录?

基本上我希望我的表名是一个外键。

例如allowed_tables 结构:

table_id | other columns |
--------------------------
table_xyz| bla bla bla   |
--------------------------

因为我在 allowed_tables 中有一个 table_xyz 的记录,所以我可以用这个名字创建一个表。如果我删除记录,表应该自动删除。如果我更改表名,则必须发生同样的情况。

编辑 1:

allowed_structures 表实际上称为贷款。它包含 loan_id 和契约(Contract)所需的其他列。插入这条记录后,我创建了一个名为 < loan_id > 的表(贷款表中必须存在的记录)。如果我更新/删除贷款表中带有 < loan_id > 的记录,我希望自动更改该表名,而不是通过 PHP 脚本。目前是通过 PHP 脚本完成的。

我需要知道哪个是执行此操作的最佳选择以及原因。谢谢!

最佳答案

这最初是为 SQL Server 编写的,但概念对于每个 RDBMS 都是相同的。

是的,这是可以实现的,但是 Curse and Blessing Dynamic SQL by Erland Sommarskog

CREATE TABLE @tbl

The desire here is to create a table of which the name is determined at run-time.

If we just look at the arguments against using dynamic SQL in stored procedures, few of them are really applicable here. If a stored procedure has a static CREATE TABLE in it, the user who runs the procedure must have permissions to create tables, so dynamic SQL will not change anything. Plan caching obviously has nothing to do with it. Etc.

Nevertheless: Why? Why would you want to do this? If you are creating tables on the fly in your application, you have missed some fundamentals about database design. In a relational database, the set of tables and columns are supposed to be constant. They may change with the installation of new versions, but not during run-time.

编辑:

在 SQL Server 中,我会为源表使用触发器 (FOR INSERT/UPDATE/DELETE) 并使用 Dynamic-SQL 我可以完全实现您想要的,但仍然我认为这疯狂

如果你想走这条路,请检查 MySQL 是否支持相同的路径。

关于mysql - 创建一个表,其名称必须是另一个表中的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422071/

相关文章:

php - 我正在尝试创建一个可重用的 php 函数,其参数用于从数据库中的表中选择数据

php - 如何从表 WHERE "function_value"中选择*?在mysql中?

mysql - 左连接运行速度比内连接快得多

php - 解码从 mysql 数据库中检索到的字符串

javascript - 有没有 'cleaner' 方法可以将 MySQL 值分配给 jQuery 变量?

MySql - 如何制作左连接表并按日期降序从表中获取前 1 个订单?

mysql - 在 mysql 中改进此查询的更好方法

php - 在 PHP 中使用 href 标签传递复选框值

mysql - Json 模式字段顺序

php - SQL索引性能?