如何用MySQL查看表外键?(mysql查看表外键)

## 前言

MySQL中,表之间通常会建立外键关联,外键可以保证表之间的数据一致性,那么如何用MySQL查看表外键呢?下面介绍几种方法,以方便使用者查看表外键。

## 正文

### 方法1:show create table

用show create table语句可以获取数据表的完整脚本,它也可以显示数据表的外键约束、索引等信息。通过在这些细节中找到外键便可查看表外键。例如:

“`SQL

mysql> SHOW CREATE TABLE orders \G;

*************************** 1. row ***************************

Table: orders

Create Table: CREATE TABLE `orders` (

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,

`order_num` int(11) DEFAULT NULL,

`member_id` int(11) NOT NULL,

`create_time` datetime NOT NULL,

PRIMARY KEY (`id`),

KEY `ix_orders_member_id` (`member_id`),

CONSTRAINT `fk_orders_member_id` FOREIGN KEY (`member_id`) REFERENCES `members` (`id`) ON DELETE CASCADE ON UPDATE CASCADE

) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set (0.00 sec)


从输出的脚本可以看到,表orders和表members建立了外键关联,外键fk_orders_member_id指向了members表的id字段。

### 方法2:information_schema
MySQL内置了information_schema库,它可以用来存储数据库的元数据,而其中也包含外键信息。我们可以通过information_schema查询外键信息,如:
```SQL
mysql> select * from information_schema.key_column_usage
where constraint_schema='test'
and referenced_table_name is not null;
+--------------------------+---------------+------------------+------------------------+-----------------------------+-----------------+---------------+---------------------+----------------+
| CONSTRAINT_CATALOG | CONSTRAINT_

数据运维技术 » 如何用MySQL查看表外键?(mysql查看表外键)