[英]A optional Many to Many relation
我對 MySQL 很陌生,必須為學校學習。 我已經為數據庫制作了 ERD,當我嘗試對其進行正向工程時,出現以下錯誤:
Executing SQL script in server
ERROR: Error 1171: All parts[![enter image description here](https://i.stack.imgur.com/PngF7.png)](https://i.stack.imgur.com/PngF7.png) of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead
SQL Code:
-- -----------------------------------------------------
-- Table `mydb`.`Vehicles_has_Armament`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Vehicles_has_Armament` (
`vehicle_ID` INT NOT NULL,
`armament_ID` INT NULL,
PRIMARY KEY (`vehicle_ID`, `armament_ID`),
INDEX `fk_Vehicles_has_Armerment_Armerment1_idx` (`armament_ID` ASC) VISIBLE,
UNIQUE INDEX `armerment_ID_UNIQUE` (`armament_ID` ASC) VISIBLE,
CONSTRAINT `fk_Vehicles_has_Armerment_Vehicles1`
FOREIGN KEY (`vehicle_ID`)
REFERENCES `mydb`.`Vehicles` (`vehicle_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Vehicles_has_Armerment_Armerment1`
FOREIGN KEY (`armament_ID`)
REFERENCES `mydb`.`Armament` (`armament_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 10 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
現在我明白了為什么我會收到錯誤,但不知道如何解決它。 我想要找到的是一種讓車輛擁有多種可能的武器的方法,但當然一種武器可以用於多輛車輛,但並不是每輛車都可以擁有武器。
以下是相關 ERD 中的三個表,當我需要此“檢查”時的表是中間表Vehicles_has_Armaments :
我看過一些 stackoverflow 線程,但它們 1. go 進入 mysql 代碼本身(不可理解,我還沒有學會它;-;)
我結合車輛表中的另一列研究了約束,表明車輛是否可以攜帶武器,但名稱約束似乎具有誤導性(在這種情況下對我來說)。
我試圖刪除中間表中武器外鍵的 Not Null 特征,但由於它是主鍵,因此不允許這樣做
我認為您誤解了如何使用多對多關系。 如果車輛和武器都存在非空值,則僅向多對多關系插入行。 如果您遇到車輛沒有給定武器的情況,那么就不要為該武器插入一行。
然后您可以在表中將兩列聲明為 NOT NULL:
CREATE TABLE IF NOT EXISTS `mydb`.`Vehicles_has_Armament` (
`vehicle_ID` INT NOT NULL,
`armament_ID` INT NOT NULL,
PRIMARY KEY (`vehicle_ID`, `armament_ID`),
...
How to many 多對多關系“可選”是僅為已知存在的配對插入行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.