Reputation: 142
Ok first off i have looked at google for hours trying to make my foreign key constraint work and no luck so far.
I will post the variations i have tried (which is basically every one i have seen on google).
This is my create statement which works perfectly, now i try to add a foreign key on Username column.
public final String CREATE_QUESTIONS_TABLE = "CREATE TABLE Questions(QuestionID INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
+ "SubmittedTime TIMESTAMP NOT NULL,"
+ "Title VARCHAR(50) NOT NULL,"
+ "Text VARCHAR(300) NOT NULL,"
+ "Username VARCHAR(10),"
+ "Rating INTEGER DEFAULT 0 NOT NULL)";
I have tried adding these next to Username:
+ "Username VARCHAR(10) CONSTRAINT username_fk FOREIGN KEY (Username) REFERENCES Users(Username),"
+ "Username VARCHAR(10) CONSTRAINT username_fk REFERENCES Users(Username),"
And a couple others which I can't remember now (I had lots of tabs open)
I know it doesn't work since when i add these i get the following when i try SELECT from it
Schema 'USERNAME' does not exist
Which means it didn't create the table and i was trying to SELECT from a table that doesn't exist.
Please help me by telling what i need to write in order to define a column as a foreign key of another table.
I am trying to set Username of table Questions a foreign key of Username (Primary Key) of table Users.
This is with Derby and Java.
Upvotes: 0
Views: 3329
Reputation: 7397
The Users table needs to be created first, followed by the Questions table.
The foreign key constraint is added at the end:
CREATE TABLE Questions
(
QuestionID INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
SubmittedTime TIMESTAMP NOT NULL,
Title VARCHAR(50) NOT NULL,
Text VARCHAR(300) NOT NULL,
Username VARCHAR(10),
Rating INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT username_fk FOREIGN KEY (Username) REFERENCES Users(Username)
)
Upvotes: 1