-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 card_type 存在则不要添加否则将这个新卡号与卡类型一起插入

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

我收到此错误:

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

提前谢谢大家帮助我:)

4

2 回答 2

0

看起来您正在尝试执行INSERT ... SELECT声明。

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

于 2012-04-25T02:19:24.563 回答
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
于 2012-04-25T02:22:26.733 回答