我的sql语句有问题吗

kmpatx3s  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(336)

它告诉我这里有个错误:

if not exists (select * from ARCUS where CUSTOMER_NO = a) 
begin 
    insert into ARCUS (CUSTOMER_NO) values (a)
end
qv7cva1a

qv7cva1a1#

此外,作为变体,您可以执行以下操作:

insert into ARCUS (CUSTOMER_NO) 
select 'a' 
where not exists (select 1 from ARCUS where CUSTOMER_NO = 'a');
nkcskrwz

nkcskrwz2#

@巴尔马有很好的解决办法,但我不能+1的答案。。。
只需在“customer\u no”上添加一个唯一键
当您使用mysql时,您还应该用小写形式编写字段和tbl名称,以提高可读性。

ALTER TABLE `arcus` ADD UNIQUE INDEX `unique_customer_no` (`customer_no`);

然后做:

INSERT IGNORE INTO `arcus` SET `customer_no` = 'a';
bogh5gae

bogh5gae3#

假设此代码位于存储过程中,则在 INSERT 查询。

if not exists (select * from ARCUS where CUSTOMER_NO = a) 
begin 
    insert into ARCUS (CUSTOMER_NO) values (a);
end

但如果 CUSTOMER_NO 是表中唯一的键,您可以通过一个查询完成:

insert ignore into ARCUS (CUSTOMER_NO) values (a);

这样做的好处是它不必在程序中。

相关问题