简体   繁体   中英

MySQL CREATE TABLE adds extra line into DDL statement

I'm using MySQL with InnoDB engine. I create a new table that contains a foreign key, eg:

CREATE TABLE rooms (
    id INTEGER NOT NULL AUTO_INCREMENT, 
    my_id VARCHAR(15), 
    house_id INTEGER, 
    PRIMARY KEY (id), 
    FOREIGN KEY(house_id) REFERENCES houses (id) ON DELETE CASCADE
)

When I use a DB tool such as DBeaver to see the details of my database and this table, I see that my foreign key house_id is missing the ON DELETE CASCADE setting, and also the foreign key house_id seems to have 2 column entries.

DBeaver also shows the DDL for this table as follows:

CREATE TABLE `rooms` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `my_id` varchar(15) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `house_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `house_id` (`house_id`),
  CONSTRAINT `rooms_ibfk_1` FOREIGN KEY (`house_id`) REFERENCES `houses` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

Why does the DDL have the extra line KEY 'house_id' ('house_id'). ? This extra line also causes my foreign key to show 2 house_id columns in my DBeaver table viewer. If I get rid of this, my ON DELETE CASCADE gets set correctly.

I'm using an ORM so I don't have control of the CREATE TABLE statement, so I'm just trying to at least understand what's going on here.

Thanks,

From the MySQL documentation on Foreign Key Constraints :

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist.

Since house_id is used in a foreign key constraint, and it doesn't already have an index, the index is added automatically.

I don't think DBeaver is showing the column twice. It's showing the column and the index, and they happen to have the same name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM