0

I have a table with million of records.

I have this query:

INSERT INTO t1 (recordA, recordB, inserttime) 
   SELECT recordA, recordB, GETDATE() 
   FROM t1 as l1 
   WHERE 
      l1.id_comp = @id_comp 
      AND l1.id_sq NOT IN (SELECT l2.id_sqa 
                           FROM leghe_formazioni as l2 
                           WHERE l2.id_comp = @id_comp)

And sometimes duplicate records and sometimes not.

The duplicate record have the same insert time.

Angus Chung
  • 1,421
  • 1
  • 9
  • 12

3 Answers3

2

Check to see if the record already exists before doing the INSERT:

IF NOT EXISTS (SELECT recordA, recordB, GETDATE() 
FROM t1 as l1 
WHERE 
    l1.id_comp = @id_comp 
    AND l1.id_sq NOT IN (
        SELECT l2.id_sqa 
        FROM leghe_formazioni as l2 
        WHERE l2.id_comp=@id_comp
    ))
INSERT INTO t1 (recordA, recordB, inserttime) 
SELECT recordA, recordB, GETDATE() 
FROM t1 as l1 
WHERE 
    l1.id_comp = @id_comp 
    AND l1.id_sq NOT IN (
        SELECT l2.id_sqa 
        FROM leghe_formazioni as l2 
        WHERE l2.id_comp=@id_comp
    )
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

Check those topics:

MySQL/PHP Inserting the same row twice

MYSQL avoid inserting same row twice

MySQL Rows Inserted Twice

Since you didn't really post much details about your problem Im afraid there is not much people can help.

You could always alter your query to maybe check if row exists before inserting it. Or try to select certain data, if result is null it means that there is no such data in DB.

Community
  • 1
  • 1
Dashovsky
  • 137
  • 9
0

You can do this way in the sql:

INSERT INTO t1 (recordA, recordB, inserttime) 
SELECT recordA, recordB, GETDATE() 
FROM t1 as l1 
WHERE 
    l1.id_comp = @id_comp 
    AND l1.id_sq NOT IN (
        SELECT l2.id_sqa 
        FROM leghe_formazioni as l2 
        WHERE l2.id_comp=@id_comp
    )
    and not exists (
      select 1 from t1 
      where t1.recordA = li.recordA and t1.recordB = li.recordB)
James Z
  • 11,838
  • 10
  • 25
  • 41