Mysql

在 MySql 工作台中創建具有 CHECK 約束的表

  • December 5, 2020

我使用 Mysql Workbench 創建了一個表ORDER,如下所示:

CREATE TABLE IF NOT EXISTS `rr`.`ORDER` (
 `Order No.` INT UNSIGNED NOT NULL COMMENT 'The order of the inspected equipment',
 `Order_Type` CHAR(8) NOT NULL COMMENT 'External or Internal work',
 `Engine_Description` VARCHAR(45) NOT NULL COMMENT 'Description of the Engine',
 `Equipment_Quantity` INT UNSIGNED NOT NULL COMMENT ' Number of the inspected equipment',
 `Required_Task` VARCHAR(8) NOT NULL COMMENT 'Whether Repair or Overhaul',
 PRIMARY KEY (`Order No.`))
ENGINE = InnoDB
COMMENT = '\n';

所以我需要知道如何制定一個約束條件,如果Order_Type欄位的值為“外部”,那麼該值的值Engine_Description 將自動為,NULL否則將添加一個值?

另外,如果我想對兩個不同的實體做同樣的事情?

正如我在評論中所說,為此目的使用觸發器

如此處所示,您已將每個約束都添加為 if 子句到您的觸發器。因為 mysql 5.x 不支持CHECK約束

另請注意,這Order是一個保留字,您不應在表名或列名中使用它們,否則您必須始終在每個查詢中使用反引號

您的欄位Engine_Description被聲明為NOT NULL所以它不能被設置為 NULL 我將它設置為一個空的描述

CREATE TABLE IF NOT EXISTS `ORDER` (
  `Order No.` INT UNSIGNED NOT NULL COMMENT 'The order of the inspected equipment',
  `Order_Type` CHAR(8) NOT NULL COMMENT 'External or Internal work',
  `Engine_Description` VARCHAR(45) NOT NULL COMMENT 'Description of the Engine',
  `Equipment_Quantity` INT UNSIGNED NOT NULL COMMENT ' Number of the inspected equipment',
  `Required_Task` VARCHAR(8) NOT NULL COMMENT 'Whether Repair or Overhaul',
  PRIMARY KEY (`Order No.`))
ENGINE = InnoDB
COMMENT = '\n';
CREATE TRIGGER before_orders_insert
BEFORE INSERT
ON `ORDER` FOR EACH ROW
BEGIN
 IF NEW.Order_Type  ='External' THEN
     SET new.`Engine_Description` = '';
 END IF;

END;
CREATE TRIGGER before_orders_UPDATE
BEFORE UPDATE
ON `ORDER` FOR EACH ROW
BEGIN
 IF NEW.Order_Type  ='External' THEN
     SET new.`Engine_Description` = '';
 END IF;

EN
INSERT INTO `ORDER` VALUES (1,'External','test descrition',1,'Repair')
,(2,'Internal','test descrition',2,'Repair')
SELECT * FROM `ORDER`
訂單號 | 訂單類型 | 引擎_描述 | 設備_數量 | 必需_任務
--------: | :--------- | :----------------- | -----------------: | :------------
 1 | 外部 | | 1 | 修理 
 2 | 內部 | 測試說明 | 2 | 修理 

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/280951