您正在对不等式进行交叉连接,这会产生大量的(重复)行。
相反,您应该在等号上执行LEFT JOIN
并过滤掉null
行。
我想它改写为:
INSERT INTO table2
(`student_id`, `studentname`, `Regno`, `class`, `date`, `session`
, `status`, `teacher_id`)
SELECT t1.* FROM table1 t1
LEFT JOIN table2 t2 ON (t1.student_id = t2.student_id)
WHERE t1.`date` BETWEEN '2011-01-01' AND '2011-05-19'
AND t1.`class` = 'AAA'
AND t2.student_id IS NULL
这里student_id
是T1和T2的主键。如果PK是(student_id数据+ teacher_id),那么查询就会变成:
INSERT INTO table2
(`student_id`, `studentname`, `Regno`, `class`, `date`, `session`
, `status`, `teacher_id`)
SELECT t1.* FROM table1 t1
LEFT JOIN table2 t2 ON (t1.student_id = t2.student_id
AND t1.teacher_id = t2.teacher_id)
WHERE t1.`date` BETWEEN '2011-01-01' AND '2011-05-19'
AND t1.`class` = 'AAA'
AND t2.student_id IS NULL /*<<-- this stays the same provided student_id is
<<-- defined as `NOT NULL` */
下面是它如何工作的。
首先我们选择(t1.student_id = t2.student_id)
;这排列了t1和t2中的所有匹配行。
因为它是左连接,所以在t1中但不在t2中的行将在t2列中具有null
值。
通过仅允许行,其中t2.student_id IS NULL
我们只从t1中选择行中没有匹配行的行。
表2是否有主键?你如何定义重复?所有列是相同的还是只是第一个...等等? – Jacob
我期望'student_id'成为PK(或者可能是组合(student_id + teacher_id) – Johan