阻止用户或错误代码插入无效数据对我来说似乎是合理的,但我不记得在任何地方看到过这个!
- 如何确保订单始终引用由同一用户创建的地址?
- 这种约束是否常见且值得推荐?我的意思是,我什至需要在设计中关心它吗?
最佳答案
由于我不希望用户能够在没有有效地址的情况下下订单,因此我将简单地删除用户表中的单独 FK,并使用地址表中的组合用户 ID - 地址 ID 字段作为一个外键。
CREATE TABLE orders AS (
--[COLUMN DEFINITIONS]
address_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
CONSTRAINT fk_usr_addr FOREIGN KEY (user_id, address_id)
REFERENCES address(user_id, id)
) ENGINE=InnoDB;
如果订单不完整并且还没有地址,那么对于多列外键这应该不是问题,因为根据 using foreign keys 上的 mysql 文档:
The MATCH clause in the SQL standard controls how NULL values in a composite (multiple-column) foreign key are handled when comparing to a primary key. MySQL essentially implements the semantics defined by MATCH SIMPLE, which permit a foreign key to be all or partially NULL. In that case, the (child table) row containing such a foreign key is permitted to be inserted, and does not match any row in the referenced (parent) table. It is possible to implement other semantics using triggers.
关于mysql - 对外键的复杂 mysql 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304149/