基于另一个引用的字段限制字段的值

2vuwiymt  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(224)

我有一个表,它的主键在其他几个表中作为外键引用。例如:

CREATE TABLE `user` (
    `user_id` int NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY  (`user_id`)
  )

  CREATE TABLE `customer` (
    `customer_id` int(11) NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    `user_id` int NOT NULL,
    PRIMARY KEY  (`customer_id`),
    CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
  )

  CREATE TABLE `product` (
    `product_id` int(11) NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    `customer_id` int NOT NULL,
    `user_id` int NOT NULL,
    PRIMARY KEY  (`user_id`),
    CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`),
    CONSTRAINT `customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`customer`);
  )

如何基于product.customer\u id的值限制product.user\u id的值。我希望product.user\u id的值始终等于customer.user\u id的值,其中customer.customer\u id=product.customer\u id

dxpyg8gm

dxpyg8gm1#

听起来你不想储存 user_idproduct table。你应该经常用 customer_id 现场。
如果出于某种奇怪的原因确实需要包含它,那么可以在上定义第二个键 customer 另一个外键关系:

CREATE TABLE `customer` (
    `customer_id` int(11) NOT NULL auto_increment,
    `name` varchar(255) NOT NULL,
    `user_id` int NOT NULL,
    PRIMARY KEY  (`customer_id`),
    CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
    UNIQUE (customer_id, user_id)  -- redundant, because customer_id is already unique
  );

CREATE TABLE `product` (
   . . .,
   FOREIGN KEY (customer_id, user_id) REFERENCES customer(customer_id, user_id)
  );

相关问题