25

我有一个表,其主键在其他几个表中作为外键引用。例如:

CREATE TABLE `X` (
  `X_id` int NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY  (`X_id`)
)
CREATE TABLE `Y` (
  `Y_id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `X_id` int DEFAULT NULL,
  PRIMARY KEY  (`Y_id`),
  CONSTRAINT `Y_X` FOREIGN KEY (`X_id`) REFERENCES `X` (`X_id`)
)
CREATE TABLE `Z` (
  `Z_id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `X_id` int DEFAULT NULL,
  PRIMARY KEY  (`Z_id`),
  CONSTRAINT `Z_X` FOREIGN KEY (`X_id`) REFERENCES `X` (`X_id`)
)

现在,我不知道数据库中有多少表包含 X 的外键,例如表 Y 和 Z。是否有一个 SQL 查询可以用来返回: 1. 具有外键的表的列表X AND 2. 哪些表实际上在外键中有值?

4

2 回答 2

57

试试这个查询:

您必须使用sysreferencessysobjects 表来获取信息

下面的查询给出了所有外键以及数据库中列名的父表

select cast(f.name as varchar(255)) as foreign_key_name
, cast(c.name as varchar(255)) as foreign_table
, cast(fc.name as varchar(255)) as foreign_column
, cast(p.name as varchar(255)) as parent_table
, cast(rc.name as varchar(255)) as parent_column
from  sysobjects f
inner join sysobjects c on f.parent_obj = c.id
inner join sysreferences r on f.id = r.constid
inner join sysobjects p on r.rkeyid = p.id
inner join syscolumns rc on r.rkeyid = rc.id and r.rkey1 = rc.colid
inner join syscolumns fc on r.fkeyid = fc.id and r.fkey1 = fc.colid
where f.type = 'F'
于 2012-08-08T14:00:26.413 回答
0

如果您只关心表名,则可以使用以下查询:

select * from  REFERENTIAL_CONSTRAINTS where CONSTRAINT_SCHEMA='schema_name' and REFERENCED_TABLE_NAME='table_name' order by TABLE_NAME

否则您可以从上述查询中获取表名,然后使用以下查询获取该特定表的外键元数据:

SELECT * FROM `information_schema`.`KEY_COLUMN_USAGE` WHERE  CONSTRAINT_SCHEMA='schema_name' and `TABLE_NAME` = 'table_name';
于 2021-04-19T09:53:12.343 回答