MySQL中按外键依赖项排序的表名列表
给定一个MySQL数据库,我如何获得一个表名列表,按照它们的外键依赖关系排序,以便删除每个表?我知道外键存储在key_COLUMN_USAGE表中,但我不确定是否有一种实用方法可以以正确的顺序获取表名。我更喜欢100%的SQL解决方案。如果外键遵循它们应该遵循的命名约定:,那么您可以做一些简单的事情,如MySQL中按外键依赖项排序的表名列表,mysql,sql,database,Mysql,Sql,Database,给定一个MySQL数据库,我如何获得一个表名列表,按照它们的外键依赖关系排序,以便删除每个表?我知道外键存储在key_COLUMN_USAGE表中,但我不确定是否有一种实用方法可以以正确的顺序获取表名。我更喜欢100%的SQL解决方案。如果外键遵循它们应该遵循的命名约定:,那么您可以做一些简单的事情,如 select table_name, group_concat(distinct constraint_name order by constraint_name) as fk_list fro
select table_name, group_concat(distinct constraint_name order by constraint_name) as fk_list
from information_schema.key_column_usage
where constraint_name rlike 'fk'
group by table_name
order by fk_list, table_name;
或者,如果外键不遵循命名约定,则
select table_name, group_concat(distinct constraint_name order by constraint_name) as fk_list
from information_schema.key_column_usage
where referenced_table_name is not null
group by table_name
order by fk_list, table_name;
试试这个:
CREATE DEFINER=`root`@`localhost` PROCEDURE `getDependencyOrder`()
BEGIN
DECLARE done INT DEFAULT 0;
declare _id int;
declare _name varchar(50);
declare _refname varchar(50);
declare cur cursor for
select table_name, referenced_table_name
from information_schema.key_column_usage
where constraint_schema = 'your_schema_name';/*************/
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
drop table if exists temp;
create temporary table temp (id int, tablename varchar(50)) engine=memory;
open cur;
set _id = 1000000;
REPEAT
FETCH cur INTO _name, _refname;
IF NOT done THEN
if not exists(select * from temp where tablename = _name) then
insert into temp(id, tablename) values(_id, _name);
set _id = _id + 1000;
end if;
end if;
UNTIL done END REPEAT;
CLOSE cur;
set done = 0;
open cur;
REPEAT
FETCH cur INTO _name, _refname;
IF NOT done THEN
if not (_refname is null) then
if _name <> _refname then
#Buscar el id de la tabla
select id into @Id from temp where tablename = _name;
#Buscar el id de la tabla de referencia, si su id es mayor, ajustar su id
select id into @refId from temp where tablename = _refname;
if @refId > @Id then
select max(id) + 1000 into _id from temp where id < @Id;
if _id is null then
select min(id) - 1000 into _id from temp;
end if;
if exists(select * from temp where id = _id) then
select max(id) into @max from temp where id < @Id;
set _id = (@max + @Id) / 2;
end if;
update temp set id = _id where id = @refId;
end if;
end if;
end if;
end if;
UNTIL done END REPEAT;
CLOSE cur;
select * from temp order by id;
drop table temp;
END
这是我通常的做法,我希望它也能对您起作用: 从“信息”\u schema.key\u column\u usage kcu中选择t.TABLE\u NAME 右连接信息\u schema.t表 在t.TABLE_NAME=kcu.TABLE_NAME上 其中t.TABLE_SCHEMA=按t.TABLE_名称顺序按t.TABLE_类型描述分组,COUNTTRUE DESC
选择按依赖项计数排序的表,大多数依赖项表将首先显示,最小依赖项表将最后显示。请注意,我首先请求视图,因为它们通常比其他表更依赖于表,但它们通常没有任何外键。那么为什么不删除所有数据库?这本质上是将表视为基于FK依赖关系的层次结构,因此,请参阅确保通过模式名称更改“your_schema_name”,应用更改并:调用getDependencyOrder;如果您的模式有大量的表,您可以将临时表中变量“_id”的类型和字段“id”的类型更改为浮点类型,而不是int。这里重要的是表的顺序,而不是id。