0

我想在data和之间添加第二个外键约束containers。当我删除一个容器时,链接到这个容器的数据也必须被删除。

表格:

mysql> DESCRIBE data;
+------------------------+--------------+------+-----+---------------------+----------------+
| Field                  | Type         | Null | Key | Default             | Extra          |
+------------------------+--------------+------+-----+---------------------+----------------
| imei                   | varchar(15)  | NO   | MUL | NULL                |                

mysql> DESCRIBE containers;
+--------------------+-------------+------+-----+---------------------+----------------+
| Field              | Type        | Null | Key | Default             | Extra          |
+--------------------+-------------+------+-----+---------------------+----------------+

| imei               | varchar(15) | NO   | MUL | NULL                |                |

我用这个语句创建了一个外键:

 mysql> ALTER TABLE `data` ADD FOREIGN KEY (`imei`) REFERENCES `containers`(`imei`) ON DELETE CASCADE;
    Query OK, 15168 rows affected (0.12 sec)
    Records: 15168  Duplicates: 0  Warnings: 0

但尚未创建外键:

 mysql> use INFORMATION_SCHEMA;
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A

    Database changed
    mysql> select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from KEY_COLUMN_USAGE where REFERENCED_TABLE_NAME = 'containers';
    +----------------+-------------+-----------------------+-----------------------+------------------------+
    | TABLE_NAME     | COLUMN_NAME | CONSTRAINT_NAME       | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
    +----------------+-------------+-----------------------+-----------------------+------------------------+
    | container_logs | imei        | container_logs_ibfk_1 | containers            | imei                   |
    +----------------+-------------+-----------------------+-----------------------+------------------------+
    1 row in set (0.16 sec)

我究竟做错了什么?

4

1 回答 1

2

并非所有存储引擎都支持外键;不支持某些 SQL 特性的存储引擎不会产生错误,而只是忽略语句(实际上 SQL 解析器是 MySQL 架构中的较高层,它使用较低级别的 API 与存储引擎进行通信)。

所以如果你使用的是MyISAM,你不能创建外键,但是不会返回错误

于 2012-12-28T14:23:43.880 回答