开发者

How to select and insert into new table without duplicate value?

I have two tables. Two tables have same fields and two table have some data. Now I want to select data in table1 and insert the the data in to table2. But I am using between, so i am confused. Please help me... Insert data in to table2 with out duplicate value.

INSERT INTO table2 
  (`student_id`, `studentname`, `Regno`, `class`, `date`, `session`
   , `status`, `teacher_id`) 
  SELECT * FRO开发者_JAVA百科M table1, table2 
  WHERE table1.date <> table2.date
    BETWEEN '2011-01-01'
    AND '2011-05-19' AND table1.class = 'AAA'


You're doing a cross join on inequality which will generate an huge amount of (duplicate) rows.
Instead you should do a LEFT JOIN on equality and filter out the null rows.

I'd rewrite it to:

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 

Here student_id is the primary key for both t1 and t2. If the PK is (student_id + teacher_id) then the query becomes:

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` */

Here's how it works.
First we select all rows where (t1.student_id = t2.student_id); this lines up all matching rows in t1 and t2.
Because it's a left join, rows that are in t1 but NOT in t2 will have null values in the t2 columns.
By only allowing rows where t2.student_id IS NULL we only select rows from t1 that have no matching row in t2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜