mysql - 对外键的复杂 mysql 约束

标签 mysql database-design constraints

阻止用户或错误代码插入无效数据对我来说似乎是合理的,但我不记得在任何地方看到过这个!

考虑下表 enter image description here

  • 如何确保订单始终引用由同一用户创建的地址?
  • 这种约束是否常见且值得推荐?我的意思是,我什至需要在设计中关心它吗?

最佳答案

由于我不希望用户能够在没有有效地址的情况下下订单,因此我将简单地删除用户表中的单独 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/

相关文章:

mysql - 我应该如何编写此 sql 查询以便只获取用户表中不存在的数字?

PHP/MySQL Count() 问题

mysql - 使用 Codeigniter 进行多重连接

mysql - 对数据库表的行进行排序

SQL 约束验证唯一值

C# 泛型约束

mysql - MySQL 的事务性 DDL 工作流

mysql - 从数据库中获取数据并过滤结果

database - 为不同的数据集构建数据库设计

swift - 使用编程约束和@IBDesignable时设计时崩溃