Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

H2 database: referring to a table in root schema from a foreign key constraint

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?

like image 688
Ivan Vučica Avatar asked May 07 '13 12:05

Ivan Vučica


People also ask

Does H2 support foreign key?

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.

How do you define a foreign key in H2?

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.

Does H2 support schema?

CREATE is a generic SQL command used to create Tables, Schemas, Sequences, Views, and Users in H2 Database server.

How do I join tables in H2 Database?

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.


1 Answers

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) ;
like image 76
Thomas Mueller Avatar answered Nov 14 '22 22:11

Thomas Mueller