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 * FROM 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 JOINon equality and filter out thenullrows.I’d rewrite it to:
Here
student_idis the primary key for both t1 and t2. If the PK is (student_id + teacher_id) then the query becomes: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
nullvalues in the t2 columns.By only allowing rows where
t2.student_id IS NULLwe only select rows from t1 that have no matching row in t2.