更改外键约束所需的最低特权是什么?


12

更改外键约束所需的最低特权是什么?

MySQL 5.5.41修复此错误后,我的迁移脚本停止工作:

  • InnoDB允许创建一个外键,该外键引用用户没有足够特权的父表。(缺陷号18790730)

我收到此错误:

SQLSTATE [42000]:语法错误或访问冲突:对表'core.users'的用户'foo'@'localhost'拒绝了1142 REFERENCES命令(SQL:更改表`user_baz`添加约束user_baz_user_id_foreign外键(`user_id))引用用户`(`id`)上的`core`.`users(在更新级联上删除级联)

这意味着我需要修复特权。我需要的最低特权是什么?

Answers:


15

您需要向角色添加“ REFERENCES”特权。


1
这种类型的“理论”答案仅是在实际中如何额外添加权限时进行额外的搜索。请参阅@Yuci的答案,其中提供了所有所需的详细信息。也就是说,GRANT REFERENCES ON test.user_baz TO 'foo'@'localhost';
John Mayor

8
GRANT [type of permission] ON [database name].[table name] TO '[username]'@'[host name or IP address]';

例如:

GRANT REFERENCES ON test.user_baz TO 'foo'@'localhost';

1

首先,如果其他所有方法均失败,请阅读文档(“使用说明”部分)。

To use `ALTER TABLE`, you need `ALTER`, `CREATE` and `INSERT` privileges for the table. Note that the user (billy) granted these privileges cannot drop the table.

下面是一个例子。

mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |    <=== now root user
+----------------+
1 row in set (0.00 sec)

mysql> CREATE TABLE a(b VARCHAR(3) PRIMARY KEY); <=== Must be PK to be FK in another table.
Query OK, 0 rows affected (0.28 sec)

mysql> CREATE TABLE c(d VARCHAR(3), KEY c_ix (d));
Query OK, 0 rows affected (0.35 sec)

mysql> GRANT ALTER, CREATE, INSERT ON c TO billy;  <=== Privileges to billy
Query OK, 0 rows affected (0.00 sec)

mysql> exit;
Bye

logon as billy

[pol@localhost dbahelper-master]$ /mysql/5.7/inst/bin/mysql -S /mysql/5.7/inst/mysql.sock -u billy -pdba

mysql> use test;
Database changed
mysql> 
mysql> ALTER TABLE c ADD CONSTRAINT fk_c_a FOREIGN KEY (d) REFERENCES a(b);
Query OK, 0 rows affected (0.64 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE c;
| c     | CREATE TABLE `c` (
  `d` varchar(3) DEFAULT NULL,
  KEY `c_ix` (`d`),
  CONSTRAINT `fk_c_a` FOREIGN KEY (`d`) REFERENCES `a` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
mysql> 
mysql> drop table c;
ERROR 1142 (42000): DROP command denied to user 'billy'@'localhost' for table 'c'
mysql> 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.