1

I used the following command to avoid duplicates in a table :

INSERT INTO mytable (num,name)
SELECT 2,'example' FROM mytable WHERE NOT EXISTS
(SELECT * FROM mytable WHERE num=2 AND name='example') LIMIT 1;

It is working but NOT if mytable is empty.

mytable also contain a AUTO_INCREMENT id.

CREATE TABLE mytable (
 id int(11) NOT NULL auto_increment,
 num int(11) NOT NULL,
 name varchar(100) NOT NULL,
 PRIMARY KEY (id)
);

Do you recommanded another method or a workaround ?

bob dylan
  • 889
  • 1
  • 9
  • 21

4 Answers4

0

In my case replacing mytable by DUAL did the trick. (But i have no idea why)

INSERT INTO mytable (num,name)
SELECT 2,'example' FROM mytable WHERE NOT EXISTS
(SELECT * FROM mytable WHERE num=2 AND name='example') LIMIT 1;

Replaced by :

INSERT INTO mytable (num,name)
SELECT 2,'example' FROM DUAL WHERE NOT EXISTS
(SELECT * FROM mytable WHERE num=2 AND name='example') LIMIT 1;

Thanks for the help.

bob dylan
  • 889
  • 1
  • 9
  • 21
  • Reason: `SELECT FROM mytable WHERE ` will return *no* records when `mytable` is empty. Using `dual`, you can also omit that `LIMIT 1` because `dual` has only one record. – JimmyB Oct 11 '16 at 14:10
0

You can create Unique column by using MySQL UNIQUE

Just update your CREATE TABLE query like below

CREATE TABLE mytable (
  id int(11) NOT NULL auto_increment,
  num int(11) NOT NULL,
  name varchar(100) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE (num) # You can define Unique column like this
);

Note: Then you no need to check Unique value when Save to Database.

And try to use normal SQL query for inserting Data

INSERT INTO mytable (num,name) VALUES(2,'example')
Sumon Sarker
  • 2,375
  • 1
  • 19
  • 32
-1

You can do something like Select * from tbl where _____ = ______

Then add if statement if results are available then insert or otherwise leave

M.suleman Khan
  • 501
  • 4
  • 17
-1

Why do not you simply use INSERT IGNORE. Also why do you want to copy the data from same table?

Gopal
  • 11
  • 3