if not exists insert in MySql

2019-02-25 03:33发布

This is MS SQL code

    if not exists (select PId from Person
             where Name = 'Name1' and Surname = 'Surname1')
    INSERT INTO [someDb].[dbo].[Person] 
        ([Name] ,[Surname])
    VALUES
        ('Name1' ,'Surname1')

can you please help me to write ekvivalent code in for my sql

thanks

标签: mysql insert
2条回答
该账号已被封号
2楼-- · 2019-02-25 04:16

In MySQL it's usually done I was usually doing it before I saw the other answer with

INSERT INTO table (fields) VALUES (values) ON DUPLICATE KEY UPDATE ID=ID;

In your case it would require a UNIQUE index on (Name,Surname) columns

查看更多
我只想做你的唯一
3楼-- · 2019-02-25 04:38

Assuming you have a unique index on (name,surname), you can use INSERT IGNORE:

INSERT IGNORE INTO `someDb`.`Person` 
        (`Name` ,`Surname`)
    VALUES
        ('Name1' ,'Surname1')
查看更多
登录 后发表回答