How to insert into values without duplicates?

104 Views Asked by At

I created new table on another database which names "workers":

CREATE TABLE workers (
ID_WORKER int(11) NOT NULL,
FNAME varchar(20) NOT NULL,
LNAME varchar(20) NOT NULL,
WORKERS_GROUP varchar(20) NOT NULL,
POSITION varchar(50) NOT NULL,
CARD_NUMBER varchar(30) NOT NULL
)

Which 'ID_WORKER' column is set on AUTO_INCREMENT. Then first time i inserted only one record:

INSERT INTO workers (FNAME, LNAME, WORKERS_GROUP, POSITION, CARD_NUMBER) 
VALUES ('Paul', 'King', 'IT', 'Programmer', '');

But in the next times i tried insert on another methods (which i'll describe what i've tried) and i had some duplicates.

What i've tried?

I've tried insert into without duplicates at least 3 methods yet:

1) By INSERT IGNORE INTO:

INSERT IGNORE INTO workers (FNAME, LNAME, WORKERS_GROUP, POSITION, CARD_NUMBER)

2) By REPLACE INTO:

REPLACE INTO workers (FNAME, LNAME, WORKERS_GROUP, POSITION, CARD_NUMBER) 
VALUES ('Paul', 'King', 'IT', 'Programmer', '');

3) By INSERT INTO ... ON DUPLICATE KEY UPDATE:

INSERT INTO workers (FNAME, LNAME, WORKERS_GROUP, POSITION, CARD_NUMBER) 
VALUES ('Paul', 'King', 'IT', 'Programmer', '') 
ON DUPLICATE KEY UPDATE FNAME = 'Paul' AND LNAME = 'King' AND WORKERS_GROUP = 'IT' AND POSITION = 'Programmer' AND CARD_NUMBER = ''

And none of them didn't work. I have no idea or clue where can I find them. Any ideas thx for any help.

EDIT

As for as duplicates are concerned can be all of them, but in that case the worker with the same FNAME, LNAME can be in the same WORKER_GROUP be he/she has to have another POSITION and CARD_NUMBER.

1

There are 1 best solutions below

5
kishan On
INSERT INTO workers (FNAME, LNAME, WORKERS_GROUP, POSITION, CARD_NUMBER)
SELECT DISTINCT w1.FNAME, w1.LNAME, w1.WORKERS_GROUP, w1.POSITION, w1.CARD_NUMBER
FROM workers w1
WHERE NOT EXISTS (SELECT 1 
                  FROM workers w2
                  WHERE w2.FNAME = w1.FNAME
                    AND w2.LNAME= w1.LNAME
                    AND w2.WORKERS_GROUP= w1.WORKERS_GROUP
                    AND w2.POSITION = w1.POSITION
                    AND s2.CARD_NUMBER = w1.CARD_NUMBER)