您正在對不等式進行交叉連接,這會產生大量的(重複)行。
相反,您應該在等號上執行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