Given a table in root schema:
CREATE TABLE user (
username VARCHAR(50),
password VARCHAR(50));
and a table in Quiz
schema:
CREATE TABLE Quiz.Results (
username VARCHAR(50),
points INT,
FOREIGN KEY (username) REFERENCES user(username));
I'm unable to actually create the foreign key, because the database claims the table user
does not actually exist. Neither can I subsequently add the foreign key:
ALTER TABLE QUIZ.RESULTS
ADD FOREIGN KEY (username) REFERENCES user (username)
Both tables are, of course, stored in the same database.
Since this is just a piece of homework, I'm more than happy to simply skip adding a foreign key. But I'm curious if this is indeed a limitation in H2, a bug, or if it works as intended.
Can I somehow refer to table user
outside the quiz
schema?
H2 Alter Table Add Foreign Key. The RazorSQL alter table tool includes an Add Foreign Key option for adding foreign keys to H2 database tables. The add foreign key function lists all of the columns of the table and allows the user to choose one or more columns to add to the foreign key for the table.
By using a Constaint Name Definition the foreign key is named explicitly, otherwise H2 assigns it a name based on it's own naming scheme e.g. CONSTRAINT_74. I feel this makes it safer to manage the constraint later by avoiding ambiguity on use of the name and referencing the name directly defined previously e.g.
CREATE is a generic SQL command used to create Tables, Schemas, Sequences, Views, and Users in H2 Database server.
You need to create a LINKED TABLE for each MySQL table that you want to use in H2. Then you will be able to use the tableName as a table in H2 in your query in AS clause of CREATE TABLE and in all other places where you need them. Finally you can drop all these linked tables when they will be no longer in use.
You would need to explicitly set the schema name if you refer to a table in a different schema. The default schema name for H2 is public
. Example:
CREATE TABLE user (
username VARCHAR(50),
password VARCHAR(50));
create schema quiz;
CREATE TABLE Quiz.Results (
username VARCHAR(50),
points INT,
FOREIGN KEY (username)
REFERENCES public.user(username));
To create the foreign key constraint later, use:
ALTER TABLE QUIZ.RESULTS
ADD FOREIGN KEY (username)
REFERENCES public.user(username) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With