Check constraint for mysql [duplicate]

感情迁移 提交于 2019-12-23 23:00:54

问题


Can anyone help me correctly write the correct syntax for a CHECK CONSTRAINT IN MYSQL. My table is as follows and am having an error on declaring a CHECK constraint for STATUS.

CREATE TABLE EventRequest (
EventNo CHAR(8) NOT NULL, 
DateHeld DATE NOT NULL, 
DateReq DATE NOT NULL,
FacNo CHAR(8)NOT NULL,
CustNo CHAR(8) NOT NULL,
DateAuth DATE,
Status CHAR(8)NOT NULL, 
EstCost DECIMAL(9,4)NOT NULL,
EstAudience INT(6) NOT NULL,
BudNo VARCHAR2(8), 
CONSTRAINT PK_EVENTREQUEST PRIMARY KEY (EventNo),
CONSTRAINT FK_FACNO FOREIGN KEY (FacNo) REFERENCES FACILITY (FacNo),
CONSTRAINT FK_CUSTNO FOREIGN KEY (CustNo) REFERENCES CUSTOMER (CustNo),
CONSTRAINT Check_Status
CHECK (Status IN ('Approved','Pending','Denied') ) ) ;

回答1:


MySQL does not support CHECK constraints.

It has been a wishlist item for years (https://bugs.mysql.com/bug.php?id=3464).

The MySQL team has posted a blog about workarounds: http://mysqlserverteam.com/new-and-old-ways-to-emulate-check-constraints-domain/

In your case you could consider:

CONSTRAINT Check_Status FOREIGN KEY (Status) REFERENCES StatusTypes (Status)

And then create a table StatusTypes with the three rows you want to restrict it to.




回答2:


Thank you all to those who tried to help, finally managed to make it work with the code below

  CREATE TABLE EventRequest  (
  EventNo VARCHAR(8) NOT NULL COMMENT 'Event number', 
  DateHeld DATE NOT NULL COMMENT 'Event date', 
  DateReq DATE NOT NULL COMMENT 'Date requested', 
  CustNo VARCHAR(8) NOT NULL COMMENT 'Customer number', 
  FacNo VARCHAR(8) NOT NULL COMMENT 'Facility number', 
  DateAuth DATE COMMENT 'Date authorized', 
  Status VARCHAR(20) NOT NULL COMMENT 'Status of event request' CHECK 
  (Status IN ('Pending', 'Denied', 'Approved')), 
  EstCost DECIMAL(15,4) NOT NULL COMMENT 'Estimated cost', 
  EstAudience DECIMAL(11,0) NOT NULL COMMENT 'Estimated audience' CHECK 
  (EstAudience > 0), 
  BudNo VARCHAR(8) COMMENT 'Budget number',
  CONSTRAINT PK_EVENTREQUEST PRIMARY KEY (EventNo),
  CONSTRAINT FK_EVENT_FACNO FOREIGN KEY (FacNo) REFERENCES FACILITY (FacNo),
  CONSTRAINT FK_CUSTNO FOREIGN KEY (CustNo) REFERENCES CUSTOMER (CustNo) ); 


来源:https://stackoverflow.com/questions/46483004/check-constraint-for-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!