我有一个表,其主键在几个其他表中被引用为外键。例如:
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,`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,PRIMARY KEY (`Z_id`),CONSTRAINT `Z_X` FOREIGN KEY (`X_id`) REFERENCES `X` (`X_id`) )
现在,我不知道数据库中有多少表包含外键到X像表Y和Z.有没有可以使用的SQL查询返回:1.具有外键到X AND的表的列表2.哪些表实际上在外键中有值
谢谢!
解决方法
尝试这个查询:
您必须使用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'