在左连接表中创建缺少的行

时间:2012-06-05 05:36:20

标签: mysql database insert

我有两个共享主键的表。我的设计很糟糕,事实证明我需要确保a1中的每条记录都有相应的记录a4

查询:

SELECT a1.id1, a4.id4
FROM  `a1` 
LEFT JOIN  `a4` ON a1.id1 = a4.id4

结果:

a1.id1.............a4.id4  
00000001    ......NULL  
00000002    ......NULL  
00001001    ......00001001  
00001002    ......00001002  

使用a1的相应键将a4中的行插入的最佳方法是什么?在上面的例子中,我需要将记录00000001和00000002插入到a4中。应该保留00001001和00001002,因为它们已经存在于a1和a4

数据库架构:

CREATE TABLE `a1` (
  `id1` int(8) unsigned zerofill NOT NULL auto_increment,
  `Shrt_Desc` varchar(200) default NULL,
  `ptype` int(5) NOT NULL,
  `userid` tinyint(5) NOT NULL,
  `submit_id` int(11) NOT NULL,
  `submit_time` int(11) NOT NULL,
  `update_id` int(11) NOT NULL,
  `update_time` int(11) NOT NULL,
  `pub` tinyint(1) default '1',
  `plate` tinyint(1) NOT NULL,
  `item` varchar(11) default NULL,
  PRIMARY KEY  (`id1`),
  KEY `fb_groupbyorder_Shrt_Desc_INDEX` (`Shrt_Desc`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=124106 ;

CREATE TABLE `a4` (
  `id4` int(8) unsigned zerofill NOT NULL,
  `Water` decimal(10,2) default NULL,
  PRIMARY KEY  (`id4`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:5)

INSERT INTO a4 (id4)
SELECT a1.id1
FROM  `a1` 
LEFT JOIN  `a4` ON a1.id1 = a4.id4
WHERE a4.id4 IS NULL

http://sqlfiddle.com/#!2/91dc1/8