具有外键在 table 1 中的约束不是 table 2 中的外键
Have constraints such that foreign key is in table 1 is not foreign key in table 2
我有一个 table 属性,现在有两个 table 的 Rent 和 sale,每个都有 property_id 作为外键。我如何保证 Rent 中的任何 property_id 都不能在 sale 中重复?如果是 MySQL 应该抛出错误。
这是租金Table,完全相似是销售
CREATE TABLE Rent
(
/*some data*/
Property_id INT NOT NULL,
PRIMARY KEY (Property_id),
FOREIGN KEY (Property_id) REFERENCES Property(Property_id) ON DELETE CASCADE
);
您可以将单个 table 与鉴别器列一起使用
示例
CREATE TABLE property (
id INT AUTO_INCREMENT,
name VARCHAR(255),
/* some data */
PRIMARY KEY (id)
);
CREATE TABLE contract (
id INT AUTO_INCREMENT,
property_id INT NOT NULL,
type VARCHAR(32) CHECK ( type IN ('rent', 'sale') ),
PRIMARY KEY (id),
FOREIGN KEY (property_id)
REFERENCES property(id) ON DELETE CASCADE
);
CREATE TABLE Rent (
id INT AUTO_INCREMENT,
/* some data */
contract_id INT NOT NULL,
contract_type VARCHAR(32) CHECK ( contract_type = 'rent'),
PRIMARY KEY (id),
FOREIGN KEY (contract_id)
REFERENCES contact(id) ON DELETE CASCADE
);
CREATE TABLE Sale (
id INT AUTO_INCREMENT,
/* some data */
contract_id INT NOT NULL,
contract_type VARCHAR(32) CHECK ( contract_type = 'sale'),
PRIMARY KEY (id),
FOREIGN KEY (contract_id)
REFERENCES contact(id) ON DELETE CASCADE
);
我有一个 table 属性,现在有两个 table 的 Rent 和 sale,每个都有 property_id 作为外键。我如何保证 Rent 中的任何 property_id 都不能在 sale 中重复?如果是 MySQL 应该抛出错误。
这是租金Table,完全相似是销售
CREATE TABLE Rent
(
/*some data*/
Property_id INT NOT NULL,
PRIMARY KEY (Property_id),
FOREIGN KEY (Property_id) REFERENCES Property(Property_id) ON DELETE CASCADE
);
您可以将单个 table 与鉴别器列一起使用
示例
CREATE TABLE property (
id INT AUTO_INCREMENT,
name VARCHAR(255),
/* some data */
PRIMARY KEY (id)
);
CREATE TABLE contract (
id INT AUTO_INCREMENT,
property_id INT NOT NULL,
type VARCHAR(32) CHECK ( type IN ('rent', 'sale') ),
PRIMARY KEY (id),
FOREIGN KEY (property_id)
REFERENCES property(id) ON DELETE CASCADE
);
CREATE TABLE Rent (
id INT AUTO_INCREMENT,
/* some data */
contract_id INT NOT NULL,
contract_type VARCHAR(32) CHECK ( contract_type = 'rent'),
PRIMARY KEY (id),
FOREIGN KEY (contract_id)
REFERENCES contact(id) ON DELETE CASCADE
);
CREATE TABLE Sale (
id INT AUTO_INCREMENT,
/* some data */
contract_id INT NOT NULL,
contract_type VARCHAR(32) CHECK ( contract_type = 'sale'),
PRIMARY KEY (id),
FOREIGN KEY (contract_id)
REFERENCES contact(id) ON DELETE CASCADE
);