Mysqlworkbench实现E-R图中任意相邻两个表做连接

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:我写的是两个表做左连接,可按实际情况进行修改。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一鹿向晗99

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值