2016-09-05 30 views
0

在運行以下程序:當最後一行被返回時,爲什麼我得到的結果包含多個行錯誤?

DELIMITER $$ 

DROP PROCEDURE IF EXISTS `portaldb`.`is_optional_type_assigned`$$ 

CREATE DEFINER=`root`@`localhost` PROCEDURE `is_optional_type_assigned`(userId int, optionalPlanId int) 
begin 
     if userId is not null and optionalPlanId is not null then 
      // Will return multiple rows 
      select conv.FeatureName from planallocation as pa 
      left join subscriptioninfo as si 
      on si.SubscriptionId = pa.SubscriptionId 
      left join plans as pl 
      on pl.PlanId = pa.CurrentPlanId 
      right join conversiontable as conv 
      on conv.ConversionId = pl.OptionalFeatureId 
      where si.UserId = userId and 
      conv.FeatureType = 'optional' into @featureList; 

      // Will return single row 
      select conv.FeatureName from conversiontable as conv 
      right join plans as pl 
      on conv.ConversionId = pl.OptionalFeatureId   
      where conv.FeatureType = 'optional' and 
      pl.PlanId = optionalPlanId into @featureName; 

      if @featureName in (@featureList) then 
       select true as isAssigned; 
      else 
       select false as isAssigned; 
      end if; 
     end if; 
    end$$ 

DELIMITER ; 

我越來越:

Error Code : 1172 
Result consisted of more than one row 

錯誤。這可能是什麼原因?前兩個select語句的結果被分配給變量,然後進行比較,如果一個集合包含另一個。

回答

2

您正在收到錯誤,因爲MySQL要求將一個正在被選中的查詢必須返回一行 - 返回零或超過一行會導致錯誤。所以你的第一個查詢,你評論返回多行,將導致錯誤。

http://dev.mysql.com/doc/refman/5.7/en/select-into.html

你可以在查詢可能更改爲類似:

select GROUP_CONCAT(conv.FeatureName) from ..... 

得到一個逗號分隔的列表結果&然後在列表中搜索@featureName - 但這可能取決於返回的結果數量。否則,你需要調整你的兩個疑問 - 可能是這樣的(注意我已經把對參數命名戈登的建議):

/ Will return single row 
select conv.FeatureName from conversiontable as conv 
right join plans as pl 
on conv.ConversionId = pl.OptionalFeatureId   
where conv.FeatureType = 'optional' and 
pl.PlanId = in_optionalPlanId into @featureName; 

select IF(count(conv.FeatureName)>0,true,false) from planallocation as pa 
left join subscriptioninfo as si 
on si.SubscriptionId = pa.SubscriptionId 
left join plans as pl 
on pl.PlanId = pa.CurrentPlanId 
right join conversiontable as conv 
on conv.ConversionId = pl.OptionalFeatureId 
where si.UserId = in_userId and 
conv.FeatureType = 'optional' and 
conv.FeatureName = @featureName; 

也許可以把它重組爲一個更有效的查詢,甚至一個單一的查詢。

+0

請問'如果@ (@featureList)'工作中的featureName?目前它不工作。 –

+0

如果我建議的重組工作 - 第二個查詢會導致真/假結果,因此不需要「(@featureList)中的if @featureName」。 – PaulF

1

你的代碼不會做你認爲它的作用。使用參數時的一個基本規則:對它們進行不同的命名,以便它們在代碼中顯而易見。

當你寫:

where si.UserId = userId and 

這被解釋爲:

where si.UserId = si.userId and 

我建議你開始一個更具可讀性和有用:

DELIMITER $$ 

DROP PROCEDURE IF EXISTS portaldb.is_optional_type_assigned$$ 

CREATE DEFINER = [email protected] PROCEDURE is_optional_type_assigned (
    in_userId int, 
    in_optionalPlanId int 
) 
BEGIN 
    if in_userId is not null and in_optionalPlanId is not null then 
     . . . 
END;$$ 

DELIMITER ; 
相關問題