首先,如果其他所有方法均失败,请阅读文档(“使用说明”部分)。
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>
GRANT REFERENCES ON test.user_baz TO 'foo'@'localhost';