delimiter $$
create procedure connection(in t1 varchar(20),in t2 varchar(20))
begin
declare v int default 0;
declare w1 int default 0;
declare w2 int default 0;
declare x1 varchar(20);
declare x2 varchar(20);
declare y1 varchar(20);
declare y2 varchar(20);
create temporary table fb as
SELECT DISTINCT
C.REFERENCED_TABLE_NAME as 父表名称
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
WHERE
C.REFERENCED_TABLE_NAME IS NOT NULL and C.TABLE_NAME=t1;
create temporary table fs as
SELECT DISTINCT
C.TABLE_NAME as 子表名称
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
WHERE
C.REFERENCED_TABLE_NAME IS NOT NULL and C.REFERENCED_TABLE_NAME=t1;
create temporary table f
(
contname varchar(20)
);
insert into f select * from fb;
insert into f select fs.子表名称 from fs;
select count(*) into v from f where contname=t2;
if v>=1 then
create temporary table findkey1 as
select
C.COLUMN_NAME scol,
C.REFERENCED_COLUMN_NAME fcol
from
INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
where
C.REFERENCED_TABLE_NAME IS NOT NULL and C.TABLE_NAME=t1 and C.REFERENCED_TABLE_NAME=t2;
select count(*) into w1 from findkey1;
if w1>=1 then
select scol into x1 from findkey1 limit 0,1;
select fcol into y1 from findkey1 limit 0,1;
set @statements1=concat('select * from ',t1,' join ',t2,' on ',t1,'.',x1,'=',t2,'.',y1); #特别注意容易错join前后必须都有空格否则会显示不存在该表,from后面也得加上空格
prepare stmt1 from @statements1;
execute stmt1;
deallocate prepare stmt1;
else
create temporary table findkey2 as
select
C.COLUMN_NAME scol,
C.REFERENCED_COLUMN_NAME fcol
from
INFORMATION_SCHEMA.KEY_COLUMN_USAGE C
where
C.REFERENCED_TABLE_NAME IS NOT NULL and C.TABLE_NAME=t2 and C.REFERENCED_TABLE_NAME=t1;
select count(*) into w2 from findkey2;
if w2>=1 then
select scol into x2 from findkey2 limit 0,1;
select fcol into y2 from findkey2 limit 0,1;
set @statements2=concat('select * from ',t1,' join ',t2,' on ',t1,'.',y2,'=',t2,'.',x2); #特别注意容易错join前后必须都有空格否则会显示不存在该表,from后面也得加上空格
prepare stmt2 from @statements2;
execute stmt2;
deallocate prepare stmt2;
end if;
end if;
end if;
end $$
delimiter ;
ps:我写的是两个表做左连接,可按实际情况进行修改。