0

I'm trying to execute this query nut it seems that it returns errors:

INSERT INTO `categories` (`name`,`path`) VALUES ('TEST 1' , 'test-1'),('TEST 2' , 'test-2'),('TEST 3' , 'test-3')
WHERE (`name`,`path`) NOT IN (SELECT `name`,`path` FROM `categories`);

Any help with this? Much appreciated.

1
  • You could add a unique key and use insert ignore into ... to insert the data Commented Jan 20, 2015 at 11:40

1 Answer 1

1

The logic you are attempted is implemented using syntax like this:

INSERT INTO `categories` (`name`,`path`)
     SELECT name, path
     FROM (SELECT 'TEST 1' as name, 'test-1' as path UNION ALL
           SELECT 'TEST 2', 'test-2' UNION ALL
           SELECT 'TEST 3' , 'test-3'
          ) t
     WHERE NOT EXISTS (SELECT 1
                       FROM categories c
                       WHERE c.name = t.name and c.path = t.path
                      );

However, you should be doing the checking in the database with a unique index. So the better solution is to do the insert and just have:

create unique index idx_categories_name_path on categories(name, path)

With an insert like:

INSERT INTO `categories` (`name`,`path`)
     SELECT name, path
     FROM (SELECT 'TEST 1' as name, 'test-1' as path UNION ALL
           SELECT 'TEST 2', 'test-2' UNION ALL
           SELECT 'TEST 3' , 'test-3'
          ) t
     ON DUPLICATE KEY UPDATE name = VALUES(name);
Sign up to request clarification or add additional context in comments.

2 Comments

The thing is the values can goes to 200 or more rows! is it ok if I proceed like u're answer ?
@user3350731 . . . There is no problem at all with handling 200 values using either method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.