如果条目不存在,则从另一个表A插入表B

时间:2015-02-12 23:14:38

标签: mysql

我希望在表格中插入" filtre"最后100条记录(ORDER BY TIME DESC 表" call_record"的限制0,100)当输入不存在时。 问题是,即使这行存在,它也会插入行。所以我在filtre中有重复的行

INSERT INTO filtre (number, sim_name, duration, time)
SELECT number, sim_name, duration, TIME
FROM `call_record`
WHERE NOT EXISTS (
  SELECT number, sim_name, duration, time
  FROM filtre 
) 
AND 
sim_name =1701
GROUP BY number
ORDER BY TIME DESC 
LIMIT 0 , 100

1 个答案:

答案 0 :(得分:0)

问题是您没有将子查询中的行与父查询相关联。您的子查询只检查' call_record'中是否存在任何行。试试这个:

INSERT INTO filtre (number, sim_name, duration, TIME) 
SELECT number, sim_name, duration, TIME 
  FROM call_record cr
 WHERE NOT EXISTS ( 
       SELECT 1
         FROM filtre f
        WHERE cr.number = f.number
          AND cr.sim_name = f.sim_name
          AND cr.time = f.time
          AND cr.duration = f.duration) 
   AND sim_name =1701 
 GROUP BY number 
 ORDER BY TIME DESC LIMIT 0 , 100

这不是最有效的方法,可以通过手头实现预期的结果。我对您的GROUP BY子句感到困惑,但如果不更好地理解您正在处理的数据集,我不确定该建议。

或者,正如symcbean在上面的注释中所建议的那样,在表上添加唯一索引并使用INSERT IGNORE可以解决问题。通常的做法是添加一个带有自动递增整数值的Id列,并将其设置为主键。假设您只插入并且从不更新记录,这应该适合您。您不希望在所有列中使用唯一索引。

INSERT IGNORE INTO filtre (id, number, sim_name, duration, TIME) 
SELECT id, number, sim_name, duration, TIME 
  FROM call_record
 WHERE sim_name = 1701 
 ORDER BY TIME DESC 
 LIMIT 0 , 100