0

I have looked for a way to try this, and so far the bet answer is using the INSERT IGNORE syntax, but my problem is that I won't be working with the id's.

Is there a way to insert a record into the database only if it doesn't exist, if you don't know the record id?

eg: I want to check if the data in col1 ('Hello') doesn't already exist.

INSERT IGNORE INTO table_name (col1, col2) values ('Hello', 1);

Existing record:

+--------------------+
| table_name         |
+--------------------+
| id  | col1  | col2 |
+--------------------+
| 2   | Hello | 1    |
|     |       |      |
Ben
  • 2,433
  • 5
  • 39
  • 69

3 Answers3

0

Your question is not clear. MYSQL works on id only. If you want it to work on col1 then you can write something like this

INSERT IGNORE INTO table_name (col1, col2) 
values ('Hello', 1) WHERE NOT EXISTS ( SELECT col1 from table_name 
                                       WHERE col1 = 'Hello')

But again add some more description to answer it properly.

Manu Singh
  • 414
  • 4
  • 16
0

I believe ON DUPLICATE KEY UPDATE suits your situation

Example query:

INSERT INTO table_name (id, col1, col2) VALUES (1,'Hello', 1)
ON DUPLICATE KEY UPDATE col1 = col1,col2 = col2;

Update: I have added id column value in query. This query check if id=1 already exists then it will not insert, if not exists it will insert

Update


If you want to check duplicate for col1 column you have to add unique constrain on this column
ALTER TABLE table_name ADD UNIQUE (col1)

SO now query of inserting and checking duplicate is:

INSERT INTO table_name (col1, col2) VALUES ('Hello', 1)
ON DUPLICATE KEY UPDATE col1 = col1,col2 = col2;

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY

Manwal
  • 23,450
  • 12
  • 63
  • 93
0

You can use ON DUPLICATE to insert a record, if existed, it will update. And if not exist, it will insert eg:

  Insert into table_name (col1, col2) values ('Hello', 1);
      ON DUPLICATE KEY UPDATE col1=values(col1),col2=values(col2)
dieuvn3b
  • 5,826
  • 3
  • 17
  • 29