SQL约束错误(匹配主键)

时间:2015-09-26 04:43:18

标签: sql oracle

SQL查询:

create table wine
wine_Id NVARCHAR2(8),
wine_name NVARCHAR2(100),
wine_vintage Smallint,
wine_price NVARCHAR2(8),
retailer_ID NVARCHAR2(8),
constraint wine_Id_pk1 primary key(wine_ID));
Foreign Key(retailer_ID) References retailer(retailer_ID));

Table created

SP2-0734: unknown command beginning "Foreign Ke..." - rest of line ignored.

然后我运行以下插入:

    insert into wine values('101', 'Grange', '2010', '750', '1001');

    insert into wine values('102', 'Grange', '2006', '700', '1001');

1 row created.

    insert into wine values('103', 'Reserve Shiraz', '2013', '10', '1001');

1 row created.

    insert into wine values('104', 'Grey Label Shiraz', '2012', '35', '1001');

1 row created.

    insert into wine values('105', 'Patricia Shiraz', '2009', '50', '1001');
1 row created.

    insert into wine values('106', 'Ten Acres Shiraz', '2012', '25', '1001');
1 row created.

    insert into wine values('107', 'Double Barrel Shiraz', '2012', '15', '1001');
1 row created.

    insert into wine values('108', 'Platinum Label Shiraz', '2006', '170', '1001');
1 row created.

    insert into wine values('103', 'Reserve Shiraz', '2013', '9', '1002');
    insert into wine values('103', 'Reserve Shiraz', '2013', '9', '1002')

ERROR at line 1:
ORA-00001: unique constraint (RYSENEVI.WINE_ID_PK1) violated`


    insert into wine values('104', 'Grey Label Shiraz', '2012', '33', '1002');

ERROR at line 1:
ORA-00001: unique constraint (RYSENEVI.WINE_ID_PK1) violated.`

    insert into wine values('105', 'Patricia Shiraz', '2009', '44', '1002');

insert into wine values('105', 'Patricia Shiraz', '2009', '44', '1002')
    *
    ERROR at line 1:
    ORA-00001: unique constraint (RYSENEVI.WINE_ID_PK1) violated`


    insert into wine values('106', 'Ten Acres Shiraz', '2012', '22', '1002');

insert into wine values('106', 'Ten Acres Shiraz', '2012', '22', '1002')
    *
    ERROR at line 1:
    ORA-00001: unique constraint (RYSENEVI.WINE_ID_PK1) violated`


    insert into wine values('107', 'Double Barrel Shiraz', '2012', '12', '1002');

ERROR at line 1:
    ORA-00001: unique constraint (RYSENEVI.WINE_ID_PK1) violated`

由于相同的主键,我无法将我的值添加到表中,所以我使用了约束方法,但它仍然不起作用,请帮忙吗?

1 个答案:

答案 0 :(得分:1)

首先,您没有使用外键约束创建表。

create table wine
wine_Id NVARCHAR2(8),
wine_name NVARCHAR2(100),
wine_vintage Smallint,
wine_price NVARCHAR2(8),
retailer_ID NVARCHAR2(8),
constraint wine_Id_pk1 primary key(wine_ID)); <=====ended the create table statement


Foreign Key(retailer_ID) References retailer(retailer_ID));<===unknown command

请改为尝试:

create table wine (
wine_Id NVARCHAR2(8),
wine_name NVARCHAR2(100),
wine_vintage Smallint,
wine_price NVARCHAR2(8),
retailer_ID NVARCHAR2(8),
constraint wine_Id_pk1 primary key(wine_ID),
constraint retailer_ID_fk1 foreign key(retailer_ID)
references retailer(retailer_ID));

其他问题似乎源于稍后创建不正确的约束。

在上面提供的表定义中,您只能拥有一个Wine_ID,但零售商表中零售商ID可以包含所需数量的零售商ID。