Java H2 数据库:从外键约束引用根模式中的表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16419680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:50:42  来源:igfitidea点击:

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

javasqldatabaseh2

提问by Ivan Vu?ica

Given a table in root schema:

给定根模式中的表:

CREATE TABLE user (
    username VARCHAR(50),
    password VARCHAR(50));

and a table in Quizschema:

Quiz模式中的表:

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 userdoes not actually exist. Neither can I subsequently add the foreign key:

我无法实际创建外键,因为数据库声称该表user实际上并不存在。我也不能随后添加外键:

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.

由于这只是一个家庭作业,我很乐意简单地跳过添加外键。但我很好奇这是否确实是 H2 的限制、错误,或者它是否按预期工作。

Can I somehow refer to table useroutside the quizschema?

我可以以某种方式引用架构user外的表quiz吗?

采纳答案by Thomas Mueller

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:

如果您引用不同架构中的表,则需要显式设置架构名称。H2 的默认架构名称是public。例子:

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) ;

回答by rahul maindargi

yes very much possible. You need to use corresponding Schema name for both tables.

是的,很有可能。您需要为两个表使用相应的架构名称。

suppose your defualt schema name is DefaultSchemathen your query will be

假设您的默认架构名称是DefaultSchema那么您的查询将是

ALTER TABLE QUIZ.RESULTS
ADD FOREIGN KEY (username) REFERENCES DefaultSchema.user (username)