添加关系(外键)失败

时间:2019-02-14 23:17:40

标签: r postgresql

我正在尝试在两个表之间添加关系(在模式mittschema中)。

以下MWE显示生成的错误。

library(data.table)
library(DBI)
con <- dbConnect(RPostgres::Postgres()
                                 , host='localhost'
                                 , port='5432'
                                 , dbname='postgres'
                                 , user="xx"
                                 , password="yy")
tbl01 <- data.table(basket=c(1L, 2L, 3L), fruit=c("Apple", "Orange", "Citrus"))
tbl02 <- data.table(basket=c(1L, 2L, 3L), color=c("Red", "Blue", "Yellow"))
RPostgres::dbWriteTable(con, name=DBI::Id(schema="mittschema", table="tbl01"), value=tbl01, overwrite = TRUE)
RPostgres::dbWriteTable(con, name=DBI::Id(schema="mittschema", table="tbl02"), value=tbl02, overwrite = TRUE)
RPostgres::dbGetQuery(con, "alter table mittschema.tbl01 add primary key (basket)")
RPostgres::dbGetQuery(con, "alter table mittschema.tbl02 add primary key (basket)")
# The following command fails
RPostgres::dbGetQuery(con, "ALTER TABLE mittschema.tbl02 ADD CONSTRAINT lnk_tbl_01_tbl_02 FOREIGN KEY ( Basket ) REFERENCES mittschema.tbl01 ( Basket );")
# Error in result_create(conn@ptr, statement) : 
#    Failed to fetch row: ERROR:  there is no unique constraint matching given keys for referenced table "tbl01"
dbDisconnect(con)

我应该如何编写命令来建立关系?

编辑:由于某种原因,它现在可以使用。

1 个答案:

答案 0 :(得分:2)

这些行仅向tmp.sql分配值。

tmp.sql <- "alter table mittschema.tbl01 add primary key (basket)"
tmp.sql <- "alter table mittschema.tbl02 add primary key (basket)"
tmp.sql <- "alter table mittschema.tbl01 add constraint unique (basket)"
tmp.sql <- "alter table mittschema.tbl02 add constraint unique (basket)"

您需要在添加外键之前执行这些SQL语句。

tmp.sql <- "alter table mittschema.tbl01 add primary key (basket)"
res <- RPostgres::dbSendQuery(con, tmp.sql)
tmp.sql <- "alter table mittschema.tbl02 add primary key (basket)"
res <- RPostgres::dbSendQuery(con, tmp.sql)
tmp.sql <- "alter table mittschema.tbl01 add constraint unique (basket)"
res <- RPostgres::dbSendQuery(con, tmp.sql)
tmp.sql <- "alter table mittschema.tbl02 add constraint unique (basket)"
res <- RPostgres::dbSendQuery(con, tmp.sql)

res <- RPostgres::dbSendQuery(con, "ALTER TABLE mittschema.tbl02 ADD CONSTRAINT lnk_tbl_01_tbl_02 FOREIGN KEY ( Basket ) REFERENCES mittschema.tbl01 ( Basket );")