1

我正在尝试创建三个表:

用户

  • 用户名
  • 用户身份

类别

  • 类别
  • 类别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 数据库的基本知识。什么?

4

2 回答 2

1

expensescategories, 指users. 因此,为usersin设置外键expenses是多余的。我相信错误来自 和 之间的冲突SET NULL操作CASCADE

当您删除 auser时,对它的categories引用将被删除(因为CASCADE),并且categories外键设置为NULLin expenses(因为SET NULL)。但是,同时,当您删除 a 时user,对它的expenses引用也将被删除(因为CASCADE)。

一个衬里:删除或中的users外键,具体取决于您要对它们做什么...expensescategories

于 2011-09-15T18:21:13.420 回答
0

在表Categories中,除了候选键 on 之外,在andcategoryID的复合上创建一个超级键。在表中,仅引用复合键。categoryIDuserIDExpenses

于 2011-09-16T08:14:50.877 回答