0
  CREATE DEFINER=`root`@`localhost` PROCEDURE `SampleProc`()
   BEGIN
           DECLARE X  INT;

           SET X = 1;
           WHILE X  <= 1890 DO
           SET @paperid=(SELECT PaperID FROM scrpd_paper_authors WHERE AuthorID=X);     
       SELECT AuthorID FROM scrpd_paper_authors WHERE PaperID=@paperid
       SET  X = X + 1;
          END WHILE;
   END$$

 DELIMITER ;

mytable                                           scrpd_paper_authrs                            

 ID     co_authors                             PaperID      AuthorId      
 ====   =========                             =========     ========
 1                                                1             1
 2                                                2             2
 3                                                3             3
 4                                                3             4
 5                                                3             5

                         mytable(expected result)

                          ID            co_authors
                         =====          ==========
                           1                 0
                           2                 0
                           3                 4,5
                           4                 3,5
                           5                 3,4

因此,现在 AuthorID 包含多行。我想使用 where 子句将这些行插入表中,但出现此错误:

“子查询返回多于一行”

例如,如果我在使用 select 时得到结果 1,2,3,我希望它们作为 ID=1 的 1,2,3 存储在 mytable (co_authors) 中。co_authors 是列名。

4

2 回答 2

0

我猜这个查询导致了错误:

SET @paperid=(SELECT PaperID FROM scrpd_paper_authors WHERE AuthorID=X);    

尝试像这样更改您的查询:

CREATE DEFINER=`root`@`localhost` PROCEDURE `SampleProc`()
BEGIN
      DECLARE X  INT;

      SET X = 1;
      WHILE X  <= 1890 DO
          INSERT INTO mytable(co_authors)
          SELECT AuthorID FROM scrpd_paper_authors WHERE PaperID in (SELECT PaperID FROM scrpd_paper_authors WHERE AuthorID=X)
          SET  X = X + 1;
      END WHILE;
END$$
于 2013-02-22T03:48:45.160 回答
0

采用

DECLARE cur CURSOR FOR select ...

然后迭代cur并插入数据

代替

SET @paperid=(SELECT ...
于 2013-02-22T03:50:32.557 回答