根据另一个引用字段限制字段的值

时间:2018-01-14 13:28:11

标签: mysql sql

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

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_id的值限制product.user_id的值。我希望product.user_id值始终等于customer.user_id的值,其中customer.customer_id = product.customer_id

1 个答案:

答案 0 :(得分:1)

听起来您不想将user_id存储在product表中。您应该始终使用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)
  );