将带有 FK 的列添加到 MySQL 5.6 中的现有 table

Add column with FK to an existing table in MySQL 5.6

大家好。希望有人能在我的实验中帮助我。

我有一个简单的 Table 可以满足我的需要,它里面甚至还有一些数据。

CREATE TABLE IF NOT exists main.test (
ID INT(11) NOT NULL, 
NAME varchar(30) NOT NULL, 
DATE_CREATED timestamp NOT NULL, 
PRIMARY KEY (ID));

但是我应该更新此 table 添加列 FK_。

如何检查 table 是否已经有字段 FK_? 如果不存在这样的列,请执行:

ALTER TABLE main.test
ADD COLUMN FK INT(11),
ADD FOREIGN KEY (FK)
REFERENCES test2(ID_test2)

因为我使用 java 我的问题的决定是使用 ResultSet。

ResultSet set = statement.executeQuery(query);
set.next();
int result = set.getInt(1); //it always return only one row
set.close();

这是我的 sql-查询:

SELECT COUNT(COLUMN_NAME) FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'main'
AND TABLE_NAME = 'test'
AND COLUMN_NAME = 'FK";

当我得到结果时,我可以决定应该使用什么查询。