2

i want to set query if row not exist

IF NOT EXISTS (SELECT id FROM table WHERE id=1)
INSERT INTO table (id, name) VALUES (1,'abx');

and that if id!=1 then values are inserted and Check if row already exists

if any solution ?

thanks in advance ...

finally i soved it

INSERT INTO table (id, name) VALUES (1,'abx') ON DUPLICATE KEY UPDATE id = 1;

thanks for your suport

4 Answers4

1

You have problem with data types - in SELECT id is compared to number (id = 1 - without apostrophes) and in INSERT id is written as a string (in apostrophes: '1').

psur
  • 4,400
  • 26
  • 36
1
INSERT IGNORE INTO `table_name` (`id`, `name`)
VALUES (1, 'abx');
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
1

MySQL does not have "IF NOT EXISTS".

For more info: How to 'insert if not exists' in MySQL?

You'll see that there are workarounds, but using MsSQL syntax won't work.

Using IGNORE should help: INSERT IGNORE INTO

Alternatively, simply let it fail.

Community
  • 1
  • 1
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
0

I think that:

INSERT IGNORE INTO table (id, name) VALUES (1,'abx');

does that you want. It'll fail silently if the INSERT was unsuccessful.

Note that the key doesn't need quotes, it's an integer, not a string

James C
  • 14,047
  • 1
  • 34
  • 43