Search code examples
mysqlif-statementalter

Add column with FK to an existing table in MySQL 5.6


Good day everyone. Hope someone can helps me in my experiments.

I have a simple Table for my needs and it's even have some data inside.

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));

But then I should update this table with adding column FK_.

How can I check if table had already has field FK_? If such column is not exist do:

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

Solution

  • As I use java decision of my problem was using ResultSet.

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

    And this is my sql-query:

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

    When I'll get a result I can decide what query I should to use.