我正在尝试创建三个表:
用户
- 用户名
- 用户身份
类别
- 类别
- 类别ID
- userID (引用用户表)
花费
- 数量
- 日期
- 费用ID
- categoryID (参考类别表) 不工作!
- userID (引用用户表) 不工作!
这是我的创建语句的代码。一切正常,直到我将“ON DELETE ...”子句添加到费用表中。
private final static String createUsersTable =
"CREATE TABLE users ("+
"userID INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), "+
"username VARCHAR(255) NOT NULL UNIQUE " +
")";
private final static String createCategoriesTable =
"CREATE TABLE categories ("+
"categoryID INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), "+
"category VARCHAR(255) NOT NULL, " +
"userID INTEGER NOT NULL, " +
"FOREIGN KEY (userID) REFERENCES users (userID) ON DELETE CASCADE"+
")";
private final static String createExpensesTable =
"CREATE TABLE expenses ("+
"expenseID INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), "+
"amount INTEGER NOT NULL, "+
"date VARCHAR(255) NOT NULL, "+
"categoryID INTEGER, "+
"userID INTEGER NOT NULL, "+
"FOREIGN KEY (categoryID) REFERENCES categories (categoryID) ON DELETE SET NULL, "+
"FOREIGN KEY (userID) REFERENCES users (userID) ON DELETE CASCADE"+
")";
这是我尝试创建表时遇到的异常:
java.sql.SQLSyntaxErrorException:外键“SQL110915104641092”无效,因为“由于删除规则限制,无法将表定义为表 ME.USERS 的依赖项。(关系导致表通过多个关系删除连接到指示的表,现有关系的删除规则为SET NULL。)。'。
我一定遗漏了一些关于 SQL 数据库的基本知识。什么?