简体   繁体   中英

MySQL syntax error regarding WHERE NOT EXISTS

I have a Chef recipe for creating Unix user IDs and deploying them across multiple nodes, to guarantee uniqueness and prevent devs from having to track them themselves. They merely name the application and it is granted a unique ID if an ID for that application doesn't already exist. If one does, it is simply returned to the script and user accounts are created on the webservers with the appropriate value.

I have a mysql database with a single table, called application_id_table which has two columns, id and application_name. id is autoincrementing and application name cannot be null (and must be unique).

Removing the Ruby from my script and making a couple of substitutions, my sql looks like this:

INSERT INTO application_id_table(application_name) VALUES('andy_test') WHERE NOT EXISTS (select 1 from application_id_table WHERE application_name = 'andy_test');

when run, I receive the syntax parsing 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 application_id_table WHERE application_name = 'a'

I recall seeing that the values statement does not allow a where clause but I don't wish to use a select statement to populate the values as I'm populating them from variables supplied from within Ruby/Chef. Anyone have an idea how to accomplish this?

You want to use insert . . . select insert . . . select insert . . . select :

INSERT INTO application_id_table(application_name)
    SELECT aname
    FROM (SELECT 'andy_test' as aname) t
    WHERE NOT EXISTS (select 1 from application_id_table ait WHERE ait.application_name = t.aname);

You should be able to plug your variable directly into the select statement, the same you would would with the VALUES statement.

Try this:

INSERT INTO application_id_table(application_name) 
select 'andy_test'
 WHERE NOT EXISTS (select 1 from application_id_table WHERE application_name = 'andy_test');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM