我需要帮助设置外键以迁移到 InnoDB。情况是我有 3 张表:工作、客户和联系人。
一个工作属于一个客户,一个工作属于一个联系人。客户有很多工作并有很多联系人。一个联系人属于一个客户并且有很多工作。我需要帮助在工作表中设置外键,以便只能插入属于选定客户的联系人。(即如果客户 A 有联系人 A1 和 A2,客户 B 有联系人 B1,一旦您选择客户 A 作为工作客户,它将拒绝除 A1 或 A2 之外的联系人条目)。这可能与外键有关,还是我必须用我选择的编程语言进行验证?
这是我的架构:
CREATE TABLE jobs(
job_id INT(11) NOT NULL AUTO_INCREMENT,
customer_id INT(11) DEFAULT NULL,
contact_id INT(11) DEFAULT NULL,
job_number INT(11) UNSIGNED NOT NULL DEFAULT 0,
status_void TINYINT(1) DEFAULT 0,
PRIMARY KEY (job_id),
INDEX active_jobs (job_number, status_void),
INDEX customer_id (customer_id),
UNIQUE INDEX job_number (job_number),
CONSTRAINT FK_jobs_contacts_contact_id FOREIGN KEY (contact_id)
REFERENCES contacts (contact_id) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT FK_jobs_customers_customer_id FOREIGN KEY (customer_id)
REFERENCES customers (customer_id) ON DELETE SET NULL ON UPDATE CASCADE
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;`
CREATE TABLE customers(
customer_id INT(11) NOT NULL AUTO_INCREMENT,
inactive TINYINT(1) DEFAULT 0,
customer_name VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY (customer_id),
UNIQUE INDEX customer_name (customer_name),
INDEX inactive (inactive)
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
CREATE TABLE contacts(
contact_id INT(11) NOT NULL AUTO_INCREMENT,
customer_id INT(11) DEFAULT NULL,
inactive TINYINT(1) DEFAULT 0,
first_name VARCHAR(50) DEFAULT NULL,
last_name VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (contact_id),
UNIQUE INDEX contact_key (customer_id, last_name, first_name),
INDEX customer_id (customer_id),
INDEX inactive (inactive),
INDEX name (last_name, first_name),
CONSTRAINT fk_contacts_customers_customer_id FOREIGN KEY (customer_id)
REFERENCES customers (customer_id) ON DELETE RESTRICT ON UPDATE CASCADE
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
我的另一个目标是设置索引以列出所有非无效的工作(status_void=0)以及所有非非活动的客户和联系人(非活动=0)。我不知道在这种情况下多列索引(工作)或两个单独的索引(客户/联系人)是否会有所帮助。
请放轻松,因为我还在学习。感谢您的时间。