108

我有一个查询来检查 mysql 用户列表以创建新用户。

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

但我得到这个错误:

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
4

2 回答 2

306

In 5.7.6 and above, you should be able to use CREATE USER

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

Note that the 5.7.6 method doesn't actually grant any permissions.


If you aren't using a version which has this capability (something below 5.7.6), you can do the following:

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

This will create the user if it doesn't exist


Note, if you are on MySQL 8, the GRANT ALL method will not create a user.

于 2013-05-16T16:24:28.407 回答
-4

我用

SELECT EXISTS (SELECT DISTINCT userFROM mysql. userWHERE user= "username") as is_user

如果存在则返回 1,如果不存在则返回 0

于 2015-05-15T08:11:56.447 回答