MySQL仅在不存在时插入或不执行任何操作

时间:2016-04-11 14:55:05

标签: mysql

如果记录不存在或者什么也不做,我试图将记录插入MySQL

插入时,我正在检查T1 ='1'并且T2 ='2'并且T3 ='3'并且vendor_brand_id = 7不存在然后只插入或者什么都不做

但这会产生语法错误,请您告诉我这个错误

这是我的架构

CREATE TABLE IF NOT EXISTS `category` (
  `category_id` int(11) NOT NULL auto_increment,
  `T1` varchar(50) default NULL,
  `T2` varchar(50) default NULL,
  `T3` varchar(50) default NULL,
  `T4` varchar(50) default NULL,
  `T5` varchar(50) default NULL,
  `T6` varchar(50) default NULL,
  `T7` varchar(50) default NULL,
  `T8` varchar(50) default NULL,
  `T9` varchar(50) default NULL,
  `T10` varchar(50) default NULL,
  `vendor_brand_id` varchar(10) default NULL,
  `created_at` timestamp NOT NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=384 DEFAULT CHARSET=latin1;

INSERT INTO `category` (`category_id`, `T1`, `T2`, `T3`, `T4`, `T5`, `T6`, `T7`, `T8`, `T9`, `T10`, `vendor_brand_id`, `created_at`) VALUES
    (377, 'one', 'two', 'three', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '7', '2016-04-11 19:32:34'),
    (378, 'one', 'two', 'three', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '7', '2016-04-11 19:32:50')

这是我的插入查询

Insert into category (T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,vendor_brand_id)
 values ('one', 'two', 'three',NULL,NULL,NULL,NULL,NULL,NULL,NULL,7) 
 select category_id from category where T1 ='one' AND T2 = 'two'  AND T3 = 'three'  AND vendor_brand_id = 7  
  FROM dual 
  WHERE NOT EXISTS
    ( SELECT *
          FROM category
         where T1 ='one' AND T2 = 'two'  AND T3 = 'three'  AND vendor_brand_id = 7  
        ) ; 

但这会产生语法错误,请您告诉我这个错误

http://sqlfiddle.com/#!9/f371e

1 个答案:

答案 0 :(得分:2)

您可以使用以下查询:

{{1}}