问一个“奇怪”的问题:sql语言可以实现最短路查询吗

「已注销」 2015-10-18 08:06:29
如题?

不知是否有人想过使用sql语言实现最短路查询的代码?
数据库中可能是:一个顶点信息表和一个边权值等信息表。

在线等,不知是否可行?
...全文
148 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhu19774279 2015-10-21
  • 打赏
  • 举报
回复
用数据库来计算,性能上不划算吧
「已注销」 2015-10-20
  • 打赏
  • 举报
回复
其中因为update/select等语句都会遍历一遍数据表中所有元祖,先仅仅考虑其复杂度而言,使用sql就将之前的复杂的几乎提升了一个平方数量级。 好像是说可以通过索引解决select每次遍历全表的问题,大家有想法实现的可以在下方讨论。
「已注销」 2015-10-20
  • 打赏
  • 举报
回复
之前尝试写了一下,今天测试了一下正确性,把代码贴出来大家可以讨论一下: 建表sql:
use school
drop table point;
create table point(
	id	int,
	val	int,
	flag	int,
	fa		int,
	primary key (id)
);
drop table line;
create table line(
	id	int,
	x	int,
	y	int,
	val int,
	flag	int,
	primary key(id)
);

插入数据就不贴了,下面是Kruskal算法的sql代码,最终会输出最小生成树的所有边权重之和:
use school;
declare @i int;
declare @ans int;
select @i=count(*) from line;
set @ans = 0;
while @i>0
begin
	declare @x int; declare @y int; declare @val int;
	declare @min_val int; declare @id_line int;
	select @min_val=min(val) from line where flag=0;
	select top 1 @id_line=id from line where flag=0 and val=@min_val;
	select @x=x,@y=y,@val=val from line where flag=0 and id = @id_line;
	update line set flag=1 where id=@id_line;
	
	declare @fa_x int; declare @fa_y int;
	select @fa_x=fa from point where id = @x;
	select @fa_y=fa from point where id = @y;
	if (@fa_x!=@fa_y)
	begin
		update point set fa = @fa_x where fa = @fa_y;
		set @ans = @ans + @min_val;
	end
	set @i = @i - 1;
end

print @ans;
ACMAIN_CHM 2015-10-19
  • 打赏
  • 举报
回复
用SQL语句理论上可以实现,但实际上节点过多后基本上SQL语句根本无法跑下来。计算量过大。 一般仍然应该是用程序算法来实现。
  • 打赏
  • 举报
回复
用递归应该可以,不过mysql的sql语发不支持递归。 所以你可以考虑用存储过程来实现递归。
rick-he 2015-10-19
  • 打赏
  • 举报
回复
http://blog.csdn.net/mchdba/article/details/39277301

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧