到目前为止,我在 invoices 表上提出了 task_id1、task_id2 等字段,它们是 task_id 字段的外键
或者,发票表可以有一个逗号分隔的 task_id 列表,这将允许每张发票的任务数量可变
不!
在 invoices 和 tasks 之间做一个多对多表,并在此 table 和 invoice 和 task 表之间进行约束。
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`invoices`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`invoices` (
`id` INT NOT NULL AUTO_INCREMENT ,
`date` DATETIME NULL ,
`amount` DECIMAL(7,2) NULL ,
`whatever` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`tasks`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`tasks` (
`id` INT NOT NULL AUTO_INCREMENT ,
`whatever` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`invoices_has_tasks`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`invoices_has_tasks` (
`invoices_id` INT NOT NULL ,
`tasks_id` INT NOT NULL ,
PRIMARY KEY (`invoices_id`, `tasks_id`) ,
INDEX `fk_invoices_has_tasks_tasks1_idx` (`tasks_id` ASC) ,
INDEX `fk_invoices_has_tasks_invoices_idx` (`invoices_id` ASC) ,
CONSTRAINT `fk_invoices_has_tasks_invoices`
FOREIGN KEY (`invoices_id` )
REFERENCES `mydb`.`invoices` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_invoices_has_tasks_tasks1`
FOREIGN KEY (`tasks_id` )
REFERENCES `mydb`.`tasks` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;