mysql 如何更新主键,如何更新主键?

在尝试更新数据库中TRUCK和TRIP表的记录时,遇到了外键约束导致的错误。由于TRIP表对TRUCK表有外键引用,不能直接更新父表的主键。解决方法是修改TRIP表的外键约束为ON UPDATE CASCADE,这样当更新父表时,子表的相关记录也会相应更新。更新脚本后,可以成功更新TRUCK表中的REGNUM字段,同时TRIP表中的关联记录也会同步更新。
摘要由CSDN通过智能技术生成

I am writing a script that has to update some rows without changing the contents of another script that creates a few tables. Another condition is that you cannot alter or drop constraints.

Contents of Create table script:

CREATE TABLE TRUCK(

REGNUM VARCHAR(10) NOT NULL,

CAPACITY DECIMAL(7) NOT NULL,

WEIGHT DECIMAL(5) NOT NULL,

STATUS VARCHAR(10) NOT NULL,

CONSTRAINT TRUCK_PKEY PRIMARY KEY(REGNUM),

CONSTRAINT TRUCK_STATUS CHECK (STATUS IN ('AVAILABLE', 'MAINTAINED', 'USED'));

and there are some row insertion statements.

CREATE TABLE TRIP(

TNUM DECIMAL(10) NOT NULL,

LNUM DECIMAL(8) NOT NULL,

REGNUM VARCHAR(10) NOT NULL,

TRIP_DATE DATE NOT NULL,

CONSTRAINT TRIP_PKEY PRIMARY KEY(TNUM),

CONSTRAINT TRIP_FKEY1 FOREIGN KEY(LNUM) REFERENCES DRIVER(LNUM)

CONSTRAINT TRIP_FKEY2 FOREGIN KEY(REGNUM) REFERENCES TRUCK(REGNUM) );

and there are some row insertion statements too.

This script is given by the lecturer and has no error.

Now, I tried:

UPDATE TRIP

SET REGNUN = 'PKR856'

WHERE REGNUM = 'SST005';

UPDATE TRUCK

SET REGNUN = 'PKR856'

WHERE REGNUM = 'SST005';

and this will give me an error "cannot delete/ update parent row. foregin key constriant.". All the row insertion statements in the given script have full information and there are row with regnum = sst005. I tried to update truck first and it won't work either. HELP PLEASE!

解决方案CONSTRAINT TRIP_FKEY1 FOREIGN KEY(LNUM) REFERENCES DRIVER(LNUM)

Check manual about MySQL foreign key:

RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.

You don't set ON DELETE and ON UPDATE options, so they will be RESTRICT by default. And you cannot update parent table primary key while row in child table exists.

You can change your CREATE TABLE like this:

CREATE TABLE TRIP(

TNUM DECIMAL(10) NOT NULL,

LNUM DECIMAL(8) NOT NULL,

REGNUM VARCHAR(10) NOT NULL,

TRIP_DATE DATE NOT NULL,

CONSTRAINT TRIP_PKEY PRIMARY KEY(TNUM),

CONSTRAINT TRIP_FKEY1 FOREIGN KEY(LNUM) REFERENCES DRIVER(LNUM) ON UPDATE CASCADE

CONSTRAINT TRIP_FKEY2 FOREGIN KEY(REGNUM) REFERENCES TRUCK(REGNUM) ON UPDATE CASCADE);

and query

UPDATE TRUCK SET REGNUN = 'PKR856' WHERE REGNUM = 'SST005';

will change keys in both tables, primary key in truck and foreign key in trip.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值