mysql crear usuario si no existe


Tengo una consulta para comprobar la lista de usuarios de mysql para crear nuevo usuario.

IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = '{{ title }}')) = 0 THEN
    CREATE USER '{{ title }}'@'localhost' IDENTIFIED BY '{{ password }}'
END IF;

Pero obtengo este error:

ERROR 1064 (42000) at line 3: 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 'IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = 'cms_localhost')) = 0 ' at line 1
Author: Konrad Borowski, 2012-11-13

3 answers

En 5.7.6 y por encima, usted debe ser capaz de utilizar CREATE USER

CREATE USER IF NOT EXISTS 'user'@'localhost' IDENTIFIED BY 'password';

Tenga en cuenta que el método 5.7.6 en realidad no otorga ningún permiso.


Si no está utilizando una versión que tenga esta capacidad (algo por debajo de 5.7.6), puede hacer lo siguiente:

GRANT ALL ON `database`.* TO 'user'@'localhost' IDENTIFIED BY 'password';

Esto creará el usuario si no existe

 225
Author: Ascherer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-16 04:47:40

No puede usar IF THEN en sentencias, marque aquí http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if

Para las funciones IF y IF ().

 -1
Author: Pankaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-13 08:58:11

Utilizo

SELECT EXISTE (SELECCIONE DISTINCT user DE mysql.user DONDE user = "nombre de usuario") como is_user

Debe devolver 1 si existe o 0 si no

 -4
Author: ingocnito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-15 08:11:56