@1-MYSQL当前用户user()与current_user()

来源:这里教程网 时间:2026-03-01 16:26:55 作者:

MYSQL在进行登陆时,会去匹配mysql库中的user表,并赋予相应的权限 在MYSQL中,有两个函数,一个是 user(),一个是 current_user();

user()是用来显示当前登陆的用户名与它对应的host, currrent_user()是用来显示当前登陆用户对应在user表中的哪一个。

mysql> select user();
+----------------------+
| user()               |
+----------------------+
| test@192.168.203.132 |
+----------------------+
1 row in set (0.00 sec)
mysql> select current_user();
+------------------+
| current_user()   |
+------------------+
| test@192.168.%.% |
+------------------+
1 row in set (0.00 sec)

一、有什么权限 所以假如我们想知道当前登陆的用户具有什么权限的话,第一步是找出当前登陆用户是用user表中的哪一个,用current_user()。

mysql> select current_user();
+----------------+
| current_user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.01 sec)

第二步用show grants命令

mysql> show grants for 'root'@'localhost';
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION        |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)

二、如果针对用户网段有限制,匹配哪一个

mysql> grant select on *.* to test@192.168.203.132 identified by '000000';
Query OK, 0 rows affected (0.00 sec)
mysql> grant select,update on *.* to 'test'@'192.168.203.%' identified by '000000';
Query OK, 0 rows affected (0.01 sec)
mysql> grant select,update,insert on *.* to 'test'@'192.168.%.%' identified by '000000';    
Query OK, 0 rows affected (0.01 sec)
mysql> grant select,update,insert,delete on *.* to 'test'@'192.%.%.%' identified by '000000';        
Query OK, 0 rows affected (0.00 sec)

可以用,进一步查看

mysql> use mysql;
Database changed
mysql> select user,host from user order by user,host;

select current_user();可以每次获取到匹配的网段的,而select user();的是具体的ip的。

mysql在登陆时会用最精确匹配user表中的帐户,host来作为当前的用户。

相关推荐