当我希望 SQL 函数返回单个值时,为什么它却返回一个表?

发布于 2025-01-14 20:35:04 字数 1236 浏览 2 评论 0原文

我想编写一个函数,因为我需要在后续问题计算具有两个公交车站的公交车票价时使用最后一站值。如果下车站点值为 Null,则将使用最后一站来计算公平性。 例如,77路公交车的测试数据: stoprank 表

我希望函数返回 sid = 77 的 stopid“40129”,这样我就可以这样做this:

select fare 
from busfare 
where boardtstop = 'xxx' and 
alightstop = if(boardstop is not null,boardstop,laststop(77))

当 alightstop 为空时,我还需要其他问题的停止值。 我希望我足够清楚,实际问题更复杂,我正在尝试简化它。


我有一个名为 stoprank 的表,其中包含以下列:stopid、sid(公交车服务 id)、stoprank。我想创建一个函数laststop,它接受公交车服务id并返回该服务的最后一站(最高停靠站)。

stoprank 表概述

我编写了以下函数:

delimiter $$
create function LastStop (serviceID int)
returns int 
DETERMINISTIC
begin
    declare laststopid int;
    
    set laststopid = (select stopid from stoprank where sid = serviceID and
    rankorder = (select max(rankorder) from stoprank where sid = serviceID));
    return laststopid;
end $$
delimiter ;

但是,不是返回一个值,而是最后一站,它返回相同值的表: 实际输出

预期输出

值是正确的,但格式错误,我不明白为什么。

I want to write a function because I need the laststop value in a subsequent question calculation the bus fare with a pair of bus stops. If the alight bus stop value is Null the last stop will be used to calculate the fair.
for example, test data for bus service 77:
stoprank table

I want the function to return stopid "40129" for sid = 77 so I can do this:

select fare 
from busfare 
where boardtstop = 'xxx' and 
alightstop = if(boardstop is not null,boardstop,laststop(77))

I also need the stop value for other questions as well when alightstop is null.
I hope I'm clear enough, the actual question is more complicated I'm trying to simplify it.


I have a table called stoprank which has columns: stopid, sid(bus service id), stoprank. I want to create a function laststop that takes in a bus service id and returns the last stop of the service(highest stoprank).

Overview of the stoprank table

I wrote the following function:

delimiter $
create function LastStop (serviceID int)
returns int 
DETERMINISTIC
begin
    declare laststopid int;
    
    set laststopid = (select stopid from stoprank where sid = serviceID and
    rankorder = (select max(rankorder) from stoprank where sid = serviceID));
    return laststopid;
end $
delimiter ;

However, instead of returning one value, the last stop, it returns a table of the same value:
actual output

expected output

The value is correct but the format is wrong, I can't figure out why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅此而已 2025-01-21 20:35:04

您应该按照这种方式编写代码。

(select stopid from stoprank where sid = serviceID order by rankorder desc limit 1);

You should write the code in this way.

(select stopid from stoprank where sid = serviceID order by rankorder desc limit 1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文