我在sql中遇到错误,无法修复此外键错误有关详细信息,请参阅desc

r7s23pms  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(280)

我已经收到了错误代码1452,我试图添加键到一个表中,以保持数据在其他表中不可用。我已经创建了表,可以使用已经输入的信息,但我想使数据库正确,所以我试图使用键。请参考下面的代码。

CREATE TABLE CUSTOMERS (
    CustID varchar(50) NOT NULL,
    Client_Name varchar(50) NOT NULL,
    Client_Address varchar(80) NOT NULL,
    PRIMARY KEY (CustID)
);

CREATE TABLE ORDERS (
    Order_ID VARCHAR(10) NOT NULL,
    Client_NameID varchar(50) NOT NULL,
    Dates varchar(10) NOT NULL,
    PRIMARY KEY (Order_ID),
    FOREIGN KEY (Client_NameID) REFERENCES CUSTOMERS(CustID)
);

SELECT * FROM CUSTOMERS;
SELECT * FROM ORDERS;

DESCRIBE Orders; /*Used to display the Table*/

ALTER TABLE ORDERS ADD Dates VARCHAR(10); /*Used to add columns into the table*/

ALTER TABLE ORDERS DROP COLUMN Date; /*Used to remove column from the table*/

INSERT INTO CUSTOMERS (CustID, Client_Name, Client_Address) VALUES 
    ('168', 'Coventry Building Services', 'Units 2-4, Binley Industrial Estate, CV3 2WL'), /*Used to insert values into the columns*/
    ('527', 'Allied Construction LTD', '34, Lythalls La Industrial Estate, NG18 5AH'),
    ('169', 'Ricoh Builds Ltd', 'Unit 12, Stoneleigh Park, CV8 2UV'),
    ('32', 'British Embassy in Tehran', '198 Ferdowski Avenue Tehran 11316-91144 Iran');

INSERT INTO ORDERS (Order_ID, Client_NameID, Dates) VALUES 
    ('CON-2237', 'Coventry Building Services', '2014-12-14'),
    ('CON-3664', 'Allied Construction LTD', '2015-01-16'),
    ('CON-2356', 'Ricoh Builds Ltd', '2015-02-12'),
    ('CON-1234', 'British Embassy in Tehran', '2015-04-16');

DELETE FROM ORDERS WHERE Client_Name='Coventry Building Services'; /*Used to delete specific 
data from the specific row and column wherever applicable*/

DROP TABLE CUSTOMERS;
DROP TABLE ORDERS;

下面是我尝试使用的表,所有这些表都有一个键,如果需要,可以将它们链接在一起
仅包含主键的customers表
包含主键和外键的orders表

qlvxas9a

qlvxas9a1#

问题在于 insert 把它放进table里 orders. Your foreign key on 客户端名称ID references 客户(custid) , but you are giving the CUSTOMERS(Client_Name) 相反。
你可能想要:

INSERT INTO ORDERS (Order_ID, Client_NameID, Dates) VALUES
    ('CON-2237', 'CON-2237', '2014-12-14');
    ('CON-3664', 'CON-3664', '2015-01-16');
    ('CON-2356', 'CON-2356', '2015-02-12');
    ('CON-1234', 'CON-1234', '2015-04-16');

笔记:
你可以表演所有的 insert 通过传递多个元组的值,在一个查询中执行,如上图所示
不要将日期存储为字符串;相反,使用 date 为此目的而存在的数据类型。我更改了查询,以便它使用适当的日期文字,这将符合 date
现在还不清楚为什么要对客户和订单的主键使用相同的值—对我来说,这使事情更难遵循。我建议只使用自动递增的主键

相关问题