0

I want to insert two values(composite keys) only when those don't already exist otherwise Mysql will give error about duplicate keys getting entered.

My this query is giving error:

INSERT INTO group_msg_response (license_id,grp_id) VALUES (1,1) WHERE NOT EXISTS (SELECT 1 FROM group_msg_response WHERE license_id=1 AND grp_id=1 )

If I run them individually they both run fine.

It is giving this error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT 1 FROM group_msg_response WHERE license_id=1 AND ' at line 1

What could be the problem? I'm doing the way as mentioned in https://dev.mysql.com/doc/refman/5.5/en/exists-and-not-exists-subqueries.html

Here is the table definition:

create table IF NOT EXISTS  msg(
 id INT UNSIGNED AUTO_INCREMENT ,
 en varchar(5000),
 hi varchar(5000),
 PRIMARY KEY(id)
) ENGINE=InnoDB;



create table  IF NOT EXISTS   group_msg(
 id INT UNSIGNED AUTO_INCREMENT ,
 msg_id INT UNSIGNED,
 lsource INT UNSIGNED  NOT NULL,
 browser CHAR(1) NOT NULL DEFAULT 'a' ,
 expiry_date DATETIME NOT NULL ,
 dated DATETIME NOT NULL,
 deleteit TINYINT DEFAULT 0 ,
 FOREIGN KEY (msg_id) 
 REFERENCES msg(id)
 ON DELETE CASCADE
 ON UPDATE CASCADE,
 PRIMARY KEY(id)
) ENGINE=InnoDB;



create table  IF NOT EXISTS   group_msg_response( 
 license_id MEDIUMINT,
 grp_id INT UNSIGNED,
 FOREIGN KEY (grp_id) 
 REFERENCES group_msg(id)
 ON DELETE CASCADE
 ON UPDATE CASCADE,
 PRIMARY KEY(license_id,grp_id)
) ENGINE=InnoDB;
user5858
  • 894
  • 1
  • 31
  • 67

1 Answers1

1

Use select, not values:

INSERT INTO group_msg_response (license_id, grp_id) 
    SELECT license_id, grp_id
    FROM (SELECT 1 as license_id, 1 as grp_id) x
    WHERE NOT EXISTS (SELECT 1
                      FROM group_msg_response gmr
                      WHERE gmr.license_id = x.license_id AND
                            gmr.grp_id = x.grp_id
                     );

Or, better yet, let the database do the work by creating a unique index/constraint:

create unique index unq_gmr_license_grp on group_msg_response(license_id, grp_id) ;

Then you can do the insert as:

INSERT INTO group_msg_response (license_id, grp_id)
    VALUES (1, 1)
    ON DUPLICATE KEY UPDATE license_id = VALUE(license_id);

The ON DUPLICATE KEY clause does nothing -- except prevent an error from occurring.

Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624