CREATE TABLE credentials (
credID SERIAL PRIMARY KEY,
usrID INTEGER NOT NULL REFERENCES users(usrID),
acctype CHAR(1) NOT NULL,
CONSTRAINT acc_constraint
CHECK (acctype = '4' OR acctype = '8' OR acctype = 'C' OR acctype = 'B'),
cardnum VARCHAR(16),
pinnum VARCHAR(8),
credactive BOOLEAN NOT NULL DEFAULT true,
created TIMESTAMP DEFAULT current_timestamp,
CONSTRAINT cardset
CHECK ( ((acctype = 'C' OR acctype = 'B') AND
cardnum IS NOT NULL AND CHARACTER_LENGTH(cardnum) = 16) OR
((acctype = '4' OR acctype = '8') AND cardnum IS NULL) ),
CONSTRAINT pinset
CHECK ( (acctype = 'C' AND pinnum IS NULL) OR
((acctype = 'B' OR acctype = '4') AND
pinnum IS NOT NULL AND CHARACTER_LENGTH(pinnum) = 4) OR
(acctype = '8' AND pinnum IS NOT NULL AND
CHARACTER_LENGTH(pinnum) = 8) )
);
错误1064(42000):您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以便在'附近使用正确的语法( credID SERIAL PRIMARY KEY, usrID INTEGER NOT NULL REFERENCES使用'在第1行
答案 0 :(得分:0)
首先是列定义,然后是约束定义,不能在列的中间放置约束定义。如果你搬家:
CONSTRAINT acc_constraint
CHECK (acctype = '4' OR acctype = '8' OR acctype = 'C' OR acctype = 'B'),
到
之后created TIMESTAMP DEFAULT current_timestamp,
然后你的桌子就可以了:
CREATE TABLE credentials (
credID SERIAL PRIMARY KEY,
usrID INTEGER NOT NULL REFERENCES users(usrID),
acctype CHAR(1) NOT NULL,
CONSTRAINT acc_constraint
CHECK (acctype = '4' OR acctype = '8' OR acctype = 'C' OR acctype = 'B'),
cardnum VARCHAR(16),
pinnum VARCHAR(8),
credactive BOOLEAN NOT NULL DEFAULT true,
created TIMESTAMP DEFAULT current_timestamp,
CONSTRAINT cardset
CHECK ( ((acctype = 'C' OR acctype = 'B') AND
cardnum IS NOT NULL AND CHARACTER_LENGTH(cardnum) = 16) OR
((acctype = '4' OR acctype = '8') AND cardnum IS NULL) ),
CONSTRAINT pinset
CHECK ( (acctype = 'C' AND pinnum IS NULL) OR
((acctype = 'B' OR acctype = '4') AND
pinnum IS NOT NULL AND CHARACTER_LENGTH(pinnum) = 4) OR
(acctype = '8' AND pinnum IS NOT NULL AND
CHARACTER_LENGTH(pinnum) = 8) )
);
<强> Example on SQL Fiddle 强>
然而,这是一项相对徒劳的练习,因为您可以在MySQL they are not enforced
中定义检查约束