mysql - 当最后返回一行时,为什么我得到的结果包含多行错误?

标签 mysql stored-procedures

在运行以下过程时:

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 语句的结果被分配给变量,然后比较一个集合是否包含另一个。

最佳答案

您收到错误是因为 MySQL 要求选择到变量中的查询必须恰好返回一行 - 返回零行或多于一行会导致错误。因此,您评论的第一个查询返回多行,将导致错误。

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

您可以将查询更改为如下内容:

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

获取单个逗号分隔的列表结果,然后在该列表中搜索@featureName - 但这可能取决于返回的结果数。否则你需要重组你的两个查询 - 可能是这样的(注意我已经合并了 Gordon 关于参数命名的建议):

/ 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;

有可能将其重组为更高效的查询,甚至是单个查询。

关于mysql - 当最后返回一行时,为什么我得到的结果包含多行错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39329026/

相关文章:

mysql - 使用存储过程在表中插入值

postgresql:嵌套插入

php - magento从1.4.0.1升级到1.4.2.0

mysql - 在sql中使用group关键字检索单行中的数据

java - 数据库连接 - java.net.UnknownHostException

MySQL 新列在 SELECT 添加,但值没有增加,存储过程

postgresql - 在 phpPgadmin 中创建程序

sql - Oracle CASE 语句?

php - 使用PDO语句时,可以使用函数安全地插入变量吗?

javascript - 如何在页面刷新之间保留变量的值?