MySQL过程不断插入复制字段

时间:2017-03-13 11:37:42

标签: mysql mysqli

这会继续插入已存在的字段,尽管它不应该。

BEGIN 

INSERT INTO ohrm_attendance_raw_data (punch_time, device_id, card_number)
SELECT punch_time, device_id, card_number
FROM ohrm_attendance_master
WHERE  ohrm_attendance_master.punch_time >= DATE_SUB(now(), INTERVAL 1 MONTH)
AND NOT EXISTS (
    SELECT 1 FROM ohrm_attendance_record WHERE ohrm_attendance_record.punch_in_user_time = ohrm_attendance_master.punch_time) 
AND NOT EXISTS (
    SELECT 1 FROM ohrm_attendance_record WHERE ohrm_attendance_record.punch_out_user_time = punch_time);

end

1 个答案:

答案 0 :(得分:0)

看起来您的字段punch_time是日期时间类型或类似的东西......所以我认为您的问题是您正在比较两个日期......以及它的问题是什么? MySQL和其他RDBMS比较包括小时,分钟,秒和毫秒...所以它可以使比较为假...你可以截断日期或给它一些格式:

使用DATE功能:

BEGIN 

    INSERT INTO ohrm_attendance_raw_data (punch_time, device_id, card_number)
    SELECT punch_time, device_id, card_number
    FROM ohrm_attendance_master
    WHERE  ohrm_attendance_master.punch_time >= DATE_SUB(now(), INTERVAL 1 MONTH)
    AND NOT EXISTS (
        SELECT 1 FROM ohrm_attendance_record WHERE DATE(ohrm_attendance_record.punch_in_user_time) = DATE(ohrm_attendance_master.punch_time)) 
    AND NOT EXISTS (
        SELECT 1 FROM ohrm_attendance_record WHERE DATE(ohrm_attendance_record.punch_out_user_time) = DATE(punch_time));
END

使用DATE_FORMAT功能:

BEGIN 

    INSERT INTO ohrm_attendance_raw_data (punch_time, device_id, card_number)
    SELECT punch_time, device_id, card_number
    FROM ohrm_attendance_master
    WHERE  ohrm_attendance_master.punch_time >= DATE_SUB(now(), INTERVAL 1 MONTH)
    AND NOT EXISTS (
        SELECT 1 FROM ohrm_attendance_record WHERE DATE_FORMAT(ohrm_attendance_record.punch_in_user_time, '%d-%b-%Y') = DATE_FORMAT(ohrm_attendance_master.punch_time, '%d-%b-%Y')) 
    AND NOT EXISTS (
        SELECT 1 FROM ohrm_attendance_record WHERE DATE_FORMAT(ohrm_attendance_record.punch_out_user_time, '%d-%b-%Y') = DATE_FORMAT(punch_time,'%d-%b-%Y'));
END