2011-08-25 69 views
1

我有兩張桌子。兩個表具有相同的字段,兩個表具有一些數據。現在我想選擇table1中的數據並將數據插入到table2中。但我正在使用,所以我很困惑。請幫助我...將數據插入到表2中,但沒有重複的值。如何選擇並插入到沒有重複值的新表中?

INSERT INTO table2 
    (`student_id`, `studentname`, `Regno`, `class`, `date`, `session` 
    , `status`, `teacher_id`) 
    SELECT * FROM table1, table2 
    WHERE table1.date <> table2.date 
    BETWEEN '2011-01-01' 
    AND '2011-05-19' AND table1.class = 'AAA' 
+0

表2是否有主鍵?你如何定義重複?所有列是相同的還是隻是第一個...等等? – Jacob

+0

我期望'student_id'成爲PK(或者可能是組合(student_id + teacher_id) – Johan

回答

2

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

+0

謝謝你soo .....我知道了..... :) – Abi

+0

感謝您的幫助... – Abi

相關問題