我有一个表,其主键在其他几个表中作为外键引用。例如:
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和2.其中哪些表实际上在外键中有值
谢谢!
答案 0 :(得分:52)
尝试此查询:
您必须使用 sysreferences 和 sysobjects 表来获取信息
下面的查询给出了所有的foriegn键以及包含数据库中列名的父表
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'
答案 1 :(得分: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';