0

我需要执行全表级扫描,因为它应该根据用户 ID 检索不止一行。

因为我曾经得到 sqlMessage 声明“子查询返回超过 1 行”。

{ Error: ER_SUBQUERY_NO_1_ROW: Subquery returns more than 1 row
  ...
  code: 'ER_SUBQUERY_NO_1_ROW',
  errno: 1242,
  sqlMessage: 'Subquery returns more than 1 row',
  sqlState: '21000',
  index: 0,
  sql: 'CALL GetLocationTag(1)' }

这是对GetLocationTag()代码的调用

DELIMITER $$

CREATE
    DEFINER = `root`@`localhost`
    PROCEDURE `someDB`.`GetLocationTag`(IN `UserId` BIGINT)
    LANGUAGE SQL
    DETERMINISTIC
    READS SQL DATA 
    SQL SECURITY DEFINER 
    COMMENT 'Retrieves Multiple Stored Location Tags, Address, Location, etc. based on User_ID'
    BEGIN
        DECLARE flag INT(11);
        DECLARE locRecord VARCHAR(255);

            IF EXISTS (SELECT * FROM `location_map` WHERE `user_id` = User_Id ) THEN  
                BEGIN
                    SELECT * INTO locRecord FROM `location_map` WHERE `user_id` = User_Id;
                    SET flag = 1;
                END;            
            ELSE
                SET flag = 0;
                SET locRecord = 0;
            END IF;

        SELECT locRecord, flag;
    END$$

DELIMITER ;

对于以下查询,

SELECT * INTO locRecord FROM `location_map` WHERE `user_id` = User_Id;

我如何需要以数组的形式检索所有行并将其存储到变量中或者我想如何编写这样的错误消息应该需要解决?

4

1 回答 1

1

使用视图而不是变量来存储获取的数据

DELIMITER $$

CREATE
    DEFINER = `root`@`localhost`
    PROCEDURE `someDB`.`GetLocationTag`(IN `User_Id` BIGINT)
    LANGUAGE SQL
    DETERMINISTIC
    MODIFIES SQL DATA
    SQL SECURITY DEFINER
    COMMENT 'Retrieves Multiple Stored Location Tags, Address, Location, etc. based on User_ID'
    BEGIN
        DECLARE flag INT(11);
        DECLARE locRecord VARCHAR(255);

            IF EXISTS (SELECT * FROM `location_map` WHERE `user_id` = User_Id ) THEN  
                BEGIN
                    SET @viewQry = CONCAT('CREATE OR REPLACE VIEW `someDB`.`temp` as SELECT *, 1 as flag FROM `location_map` WHERE `user_id` = ',User_Id,';');
                    PREPARE stmt FROM @viewQry; 
                    EXECUTE stmt; 
                    DEALLOCATE PREPARE stmt;
                    SELECT * FROM temp;
                END;            
            ELSE
                SELECT 0 AS locRecord, 0 AS flag;
            END IF;
    END$$

DELIMITER ;
于 2019-03-08T08:44:09.253 回答