SQL错误 - 无法添加外键约束

时间:2014-10-21 12:04:01

标签: sql foreign-keys

我正在尝试使用java(jdbc)在数据库中创建一些表。 下面的“代码”只是两个字符串,每个字符串包含一个SQL CREATE TABLE更新,一个用于表“store_sales”,另一个用于表“store_returns” 我得到了 java.sql.SQLException:无法添加外键约束

当我尝试使store_returns.sr_ticket_number在“代码”的最后一行引用store_sales.ss_ticket_number的外键时发生这种情况

有什么想法吗?提前谢谢。

"CREATE TABLE IF NOT EXISTS store_sales ("
        + "ss_sold_date_sk int,"
        + "ss_sold_time_sk int,"
        + "ss_item_sk int not null,"
        + "ss_customer_sk int,"
        + "ss_cdemo_sk int,"
        + "ss_hdemo_sk int,"
        + "ss_addr_sk int,"
        + "ss_store_sk int,"
        + "ss_promo_sk int,"
        + "ss_ticket_number int not null,"
        + "primary key (ss_item_sk,ss_ticket_number),"
        + "foreign key (ss_sold_date_sk) references date_dim (d_date_sk),"
        + "foreign key (ss_sold_time_sk) references time_dim (t_time_sk),"
        + "foreign key (ss_item_sk) references item (i_item_sk),"
        + "foreign key (ss_customer_sk) references customer (c_customer_sk),"
        + "foreign key (ss_cdemo_sk) references customer_demographics (cd_demo_sk),"
        + "foreign key (ss_hdemo_sk) references household_demographics (hd_demo_sk),"
        + "foreign key (ss_addr_sk) references customer_address (ca_address_sk),"
        + "foreign key (ss_store_sk) references store (s_store_sk),"
        + "foreign key (ss_promo_sk) references promotion (p_promo_sk)"
        + ")"

        ,

        "CREATE TABLE IF NOT EXISTS store_returns ("
        + "sr_return_date_sk int,"
        + "sr_return_time_sk int,"
        + "sr_item_sk int not null,"
        + "sr_customer_sk int,"
        + "sr_cdemo_sk int,"
        + "sr_hdemo_sk int,"
        + "sr_addr_sk int,"
        + "sr_store_sk int,"
        + "sr_reason_sk int,"
        + "sr_ticket_number int not null,"
        + "primary key (sr_item_sk,sr_ticket_number),"
        + "foreign key (sr_return_date_sk) references date_dim (d_date_sk),"
        + "foreign key (sr_return_time_sk) references time_dim (t_time_sk),"
        + "foreign key (sr_item_sk) references item (i_item_sk),"
        + "foreign key (sr_customer_sk) references customer (c_customer_sk),"
        + "foreign key (sr_cdemo_sk) references customer_demographics (cd_demo_sk),"
        + "foreign key (sr_hdemo_sk) references household_demographics (hd_demo_sk),"
        + "foreign key (sr_addr_sk) references customer_address (ca_address_sk),"
        + "foreign key (sr_store_sk) references store (s_store_sk),"
        + "foreign key (sr_reason_sk) references reason (r_reason_sk),"
        + "foreign key (sr_ticket_number) references store_sales (ss_ticket_number)"
        + ")"

1 个答案:

答案 0 :(得分:4)

您无法在store_sales中的(ss_item_sk,ss_ticket_number)组合外键的一部分中添加外键约束。对于外键约束,您必须处理引用表的主键的所有部分。

这样的东西
foreign key (sr_item_sk, sr_ticket_number) references store_sales (ss_item_sk,ss_ticket_number)

应该有效