我无法创建下表。是因为复合主键吗?我已经为用户和titles表添加了信息,以防代码中出现问题。
CREATE TABLE store
(
short_name VARCHAR(5) NOT NULL,
name VARCHAR(30) NOT NULL,
address1 VARCHAR(50) NOT NULL,
address2 VARCHAR(20),
city VARCHAR(30) NOT NULL,
state VARCHAR(30) NOT NULL,
zip VARCHAR(10) NOT NULL,
phone VARCHAR(15) NOT NULL,
CONSTRAINT store_pk PRIMARY KEY (short_name)
);
CREATE TABLE publishers
(
name VARCHAR(50) NOT NULL,
status TINYINT DEFAULT 1 NOT NULL,
CONSTRAINT publishers_pk PRIMARY KEY (name)
);
CREATE TABLE users
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(70) NOT NULL,
password VARCHAR(60),
address1 VARCHAR(50) NOT NULL,
address2 VARCHAR(20),
city VARCHAR(30) NOT NULL,
state VARCHAR(30) NOT NULL,
zip VARCHAR(10) NOT NULL,
phone VARCHAR(15),
email VARCHAR(90),
store VARCHAR(5),
admin TINYINT DEFAULT 0 NOT NULL,
mail_list TINYINT DEFAULT 0 NOT NULL,
active TINYINT DEFAULT 0 NOT NULL,
CONSTRAINT users_pk PRIMARY KEY (id),
CONSTRAINT users_fk FOREIGN KEY (store)
REFERENCES store (short_name)
ON DELETE SET NULL
ON UPDATE CASCADE
);
CREATE TABLE titles
(
id INT NOT NULL AUTO_INCREMENT,
publisher VARCHAR(50),
title VARCHAR(50) NOT NULL,
status ENUM('active', 'announced', 'inactive'),
discount TINYINT NOT NULL,
CONSTRAINT title_pk PRIMARY KEY (id),
CONSTRAINT title_fk FOREIGN KEY (publisher)
REFERENCES publishers (name)
ON DELETE SET NULL
ON UPDATE CASCADE
);
CREATE TABLE subscriptions
(
user INT,
title INT,
quantity TINYINT DEFAULT 1 NOT NULL,
CONSTRAINT subscription_pk PRIMARY KEY (user, title),
CONSTRAINT subscription_user_fk FOREIGN KEY (user)
REFERENCES users (id)
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT subscription_title_fk FOREIGN KEY (title)
REFERENCES titles (id)
ON DELETE SET NULL
ON UPDATE CASCADE
);
答案 0 :(得分:2)
使用表定义,只有subscriptions
表出现问题,这是因为ON DELETE SET NULL
子句。 user
表格中的title
和subscriptions
列都定义为NOT NULL
!
答案 1 :(得分:0)
主键定义错误。 constraint title_pk primary key (id)
这些都是错误的。它们应该像primary key(id)
答案 2 :(得分:0)
它可能在外键约束上失败。
运行:
SHOW ENGINE INNODB STATUS\G
查看“最新的外键错误”部分。这应该告诉你这个问题。
如果用户和/或标题表尚不存在,则应在创建表之前运行此表:
set foreign_key_checks = 0;
如果这些表确实存在,则父列(即user.id)和子列(即用户)之间的数据类型可能不匹配。