在SQL中模拟环(代数)

时间:2015-06-01 13:20:44

标签: mysql sql algebra

我正在创建小型配置文件查看器,我想在SQL中模拟环。这个怎么运作?简单来说: 我的桌子上有5个用户。当我从中间到我的实验(如用户编号2,3,4)获得一个时,下一个和上一个用户是CURRENT_USER_ID + - 1.但是当我选择用户编号1或5时,它不像之前那样简单。所以如果我有像代数环这样的工具,那很容易。我可以模拟它吗?

哦,我正在使用MySQL。

1 个答案:

答案 0 :(得分:3)

像这样: SQLFIDDLE

set @curr_user = 1;
set @maxid = (select max(u1.id) maxid from users u1);
set @minid = (select min(u2.id) minid from users u2);
set @next_user = (if(@curr_user = @maxid
                           ,@minid
                           ,@curr_user +1));
set @prev_user = (if(@curr_user = @minid
                           ,@maxid
                           ,@curr_user - 1));

SELECT t1.name as prevuser, t2.name as curruser, t3.name as nextuser
FROM users t1
join users t2
on 1=1
JOIN users t3
on 1=1
WHERE t1.id = @prev_user
AND t2.id = @curr_user
and t3.id = @next_user
编辑:我做了一个小调整,所以即使丢失了id也可以工作,假设你有用户1,3,4,5,7这将获得用户4,5,7如果当前是5 {{ 3}}

set @curr_user = 3;
set @maxid = (select max(u1.id) maxid from users u1);
set @minid = (select min(u2.id) minid from users u2);
set @nextid = (select min(id) from users where id > @curr_user );
set @previd = (select max(id) from users where id < @curr_user );
set @next_user = (if(@curr_user = @maxid
                           ,@minid
                           ,@nextid));
set @prev_user = (if(@curr_user = @minid
                           ,@maxid
                           ,@previd));

SELECT t1.name as prevuser, t2.name as curruser, t3.name as nextuser
FROM users t1
join users t2
on 1=1
JOIN users t3
on 1=1
WHERE t1.id = @prev_user
AND t2.id = @curr_user
and t3.id = @next_user