2012-04-25 83 views
-2
insert into creditcard_info (member_id,card_type,card_number) 
values ('1','Discover','555') 
where not exists (
     select * from creditcard_info 
     where card_number='555' and 
      card_type='Discover') 

我希望能够检查一个身份证号码已经存在.. 如果CARD_NUMBER存在,然后卡CARD_TYPE存在不添加 与卡一起插入其他新卡号键入mysql插入不存在语法错误。我不知道什么是错的

我很难与插入某个数字不存在的表中。

即时得到这个错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL 
server version for the right syntax to use near 'where not exists (select * from 
creditcard_info where card_number='555')' at line 2 

谢谢大家提前帮助我:)

+1

创建'CARD_NUMBER + card_type'领域 – zerkms 2012-04-25 02:15:41

+0

的事情是,卡类型设置为仅几类,是不是唯一的唯一索引....数量也可以相同与不同的类型....我只是想它,以便它检查是否存在卡类型和卡号存在作为记录 – user1235103 2012-04-25 02:39:07

回答

0

它看起来像你想执行INSERT ... SELECT声明。

但是,在两个字段中添加唯一索引应该更有效。

0

您需要创建一个多列唯一索引。代码如下:

ALTER TABLE creditcard_info ADD UNIQUE idx_card_number_card_type(card_number,card_type); 

这应该作为单独的查询运行。你需要添加一次。
其他可能的选择是在插入触发器之前添加,如果条件比简单的唯一检查更复杂。 这里是create trigger语法:

Create Trigger card_type_unique_card_number_exists Before Insert on creditcard_info 
    FOR EACH ROW BEGIN 
     DECLARE it_exists INT; 
     Set it_exists=(select count(*) from creditcard_info where card_number='555' and card_type='Discover'); 
     If it_exists>0 Then 
      #Throw a meaningful exception by let's say inserting into a table which doesn't exist or something 
     END IF; 
    END 
+0

事情是卡类型只设置为几种类型,并不是独特的....也可以是不同类型的数字.... 我只是想它,以便它检查是否存在卡类型和卡号作为记录存在 – user1235103 2012-04-25 02:26:44

+0

上述唯一索引将使组合独一无二。它不会被应用于列表中的每一列。您的代码有与card_type'XOR' card_number类似的行,但组合应该是唯一的。如果这仍不是你的意思,你可以在插入触发器之前进行。我会在一分钟之内将它添加到那里。 – 2012-04-25 02:40:10

相关问题