我正在尝试从Membership_benefit表中获取NUMSESSION值。我的函数有一个福利ID和一个成员ID作为参数,而Membership_benefit需要这两个值,否则它将返回多行。
这是功能的要旨
`CREATE OR REPLACE FUNCTION benefit_when(_benefitid integer, _membershipid
integer) RETURNS text AS $$
DECLARE
bfrec record;
BEGIN
if _membershipid is not null then
select
benefit.*,
membership_benefit.numsession as numsession
from benefit
left join membershiptype on benefit.membershiptypeid=membershiptype.id
left join membership_benefit on _membershipid = membership_benefit.membershipid
where benefit.id=_benefitid
AND (membership_benefit.membershipid is null or membership_benefit.membershipid = _membershipid);`
未正确返回numsession值。如果我打印两个参数的值并简单地查询数据库,它将返回正确的参数,但不会在此函数中返回。您是否可以像我在这里一样使用变量进行联接,如果没有,是否有更好的方法通过我拥有的两个参数来获取正在寻找的数字?
谢谢。
答案 0 :(得分:0)
更改查询:
select
benefit.*,
membership_benefit.numsession as numsession
from benefit
left join membershiptype on benefit.membershiptypeid=membershiptype.id
left join membership_benefit on _membershipid = membership_benefit.membershipid
where benefit.id=_benefitid
变成这样:
select benefit.*,
membership_benefit.numsession as numsession
from benefit
left join membershiptype on
benefit.membershiptypeid=membershiptype.id
where benefit.id=_benefitid
and _membershipid = membership_benefit.membershipid
答案 1 :(得分:0)
如果您只想使用numsession
,则不确定为什么要进行外部联接。这是您真正想要的吗?
select mb.numsession
from membership_benefit mb
where mb.membershipid = _membershipid and
mb.benefitid = _benefitid;
如果您总是希望获得好处,请与以下信息一同显示:
select b.*, mb.numsession as numsession
from benefit b join
membership_benefit mb
on mb.benefitid = b.id and
mb.membershipid = _membershipid and
b.id =_benefitid
where b.id = _benefitid;
我推测您想要这两件事之一。