快捷方式在创建表时分配主键

时间:2013-03-29 19:04:54

标签: mysql

在创建表时,使用快捷查询分配主键的正确方法是什么?

以下是我的快捷方式示例:

create table booking_product (
`id` int(10) not null constraint `booking_product_id` primary key auto_increment ,
`bookingId` int(10) not null,
`serviceId` int(10) not null,
`date` date not null,
`price` decimal(30,15) not null,
`qty` int(1) not null,
`currencyId` int(10) not null,
`total` decimal(30,15) not null,
`roomInclusion` text null default null,

foreign key booking_product(bookingId) references booking(id) on update cascade on delete cascade,
foreign key booking_product(serviceId) references service(id) on update cascade on delete set null,
foreign key booking_product(currencyId) references currency(id) on update cascade on delete set null
) engine = InnoDB;
  • 第2行的注意事项我尝试分配主键,但此查询错误并产生错误。如果我尝试仅使用id int(10) not null primary key auto_increment ,,我会收到错误:Duplicate key name 'booking_product'

2 个答案:

答案 0 :(得分:3)

如果您使用constraint booking_product_id,则不会收到有关Duplicate key name 'booking_product'的错误,因为SQL解析器会在第一次错误时停止。

删除constraint booking_product_id并使用

foreign key bookingId_fk(bookingId) references booking(id)
    on update cascade
    on delete cascade,
foreign key serviceId_fk(serviceId) references service(id)
    on update cascade
    on delete set null,
foreign key currencyId_fk(currencyId) references currency(id)
    on update cascade
    on delete set null

答案 1 :(得分:1)

我知道你选择了一个答案但是当我将你的创建语句简化为下面的代码时,我得到了它的工作。现在,通过Oswald添加的“drop constraint”请求,您可能拥有所需的一切:

create table booking_product (
id int(10) not null auto_increment,
PRIMARY KEY(id),  <<<<< this worked for me...
bookingId int(10) not null,
serviceId int(10) not null,
date date not null,
price decimal(30,15) not null,
qty int(1) not null,
currencyId int(10) not null,
total decimal(30,15) not null,
roomInclusion text null default null)

同样,我只是接近你提出的主要问题。

希望这有帮助。

相关问题