如何跟踪不同表中的ID(主要)?

时间:2014-09-01 13:07:51

标签: php mysql

我将从一个例子开始,以便明确我要问的是什么。

Templates
template_id, Name
1, Light Blue
2, Red
3, Sky Blue
4, Yellow

template_id是主要和自动增量。

Products
product_id, product_name, template_id

Users
user_id, user_name, template_id

Categories
category_id, category_name, template_id

有6个以上的表更像这样引用template_id。

所有这些表格中的默认 template_id为(表示未分配模板)

我需要一种方法将这些引用存储在某处,这样如果我尝试删除模板,我的php应用程序将检查它是否正在使用。我知道这是一种外键概念,但我不确定我是否可以在外键列中获得零值,所以我感觉有点卡住了。您有什么建议来解决这个问题?如何在不同的表中跟踪模板ID的使用位置。

更新

我尝试按建议添加外键...

ALTER TABLE `Templates`  
ADD CONSTRAINT `Templates_ibfk_1` 
FOREIGN KEY (`template_id`) REFERENCES `Products` (`template_id`),
ADD CONSTRAINT `Templates_ibfk_2` 
FOREIGN KEY (`template_id`) REFERENCES `Users` (`template_id`)

我在哪里可以查看这些是否已添加?我尝试使用PhpMyAdmin查看Templates表的结构,但在那里找不到任何提到外键的东西?

2 个答案:

答案 0 :(得分:0)

在Mysql中使用参考视图,这将有助于您以后自动管理/跟踪记录。

  ALTER TABLE `Templates`  ADD CONSTRAINT `Templates_ibfk_1` FOREIGN KEY (`template_id`) REFERENCES `Products` (`template_id`),ADD CONSTRAINT `Templates_ibfk_2` FOREIGN KEY (`template_id`) REFERENCES `Users` (`template_id`)

要详细了解详情,请阅读此Link

答案 1 :(得分:0)

我会将InnoDB用于我的表,建立外键约束并让MySQL处理问题而不是尝试以编程方式复制此功能。

我也会避免使用0作为默认模板并创建一个默认(无模板),这将是template_id = 1

为错误保留0和/或-1。