MySQL错误:子查询返回多行

时间:2011-03-16 11:22:56

标签: mysql sql

在我的查询中,我提取了三列(比如A,B和摘要)

摘要基于B和A.

我必须使用子查询来获取基于A和B的摘要。

问题:

对于A的一个值(比如A1)和一个B的值(比如B1),我在一列中得到两个Summary值(比如Summ1和Summ2)。

因此它给出错误:

 Subquery returns more than one row 

相反,我想在表格中显示如下:

 A1     B1     Summ1
 A1     B1     Summ2  

我该怎么办?

QUERY:

SELECT a.FundIDRecv,a.SubscribeDt, b.FundName, 
(
   SELECT c.PricePerWeek
   FROM tbl_Hive c
   WHERE c.FundID IN 
   (
      SELECT FundID from tbl_FundStatic 
      WHERE FundID IN
      (
          SELECT FundIDSend
          FROM tbl_FundSubscriptions 
          WHERE FundIDRecv = a.FundIDRecv

      )
      AND UserID = '14'
   )
) as Price
FROM tbl_FundSubscriptions a, tbl_Hive b
WHERE a.FundIDRecv = b.FundID

AND a.FundIDRecv
IN (

SELECT FundIDRecv
FROM tbl_FundSubscriptions
WHERE FundIDSend
IN (

SELECT FundID
FROM tbl_FundStatic 
WHERE UserID = '14'
)
)
Group by a.FundIDRecv

c.PricePerWeek的SELECT语句会生成该错误

4 个答案:

答案 0 :(得分:1)

您不需要使用子查询来对A列和B列求和。

试试

SELECT A,B,(A+B) as 'sum'
FROM table

发布您的查询以帮助您。

<强>更新

在你的查询中,在子查询结果中返回多行是正常的,也许你想这样做:SUM(c.PricePerWeek)

SELECT a.FundIDRecv,a.SubscribeDt, b.FundName, 
(
   SELECT SUM(c.PricePerWeek)
   FROM tbl_Hive c
   WHERE c.FundID IN 
   (
      SELECT FundID from tbl_FundStatic 
      WHERE FundID IN
      (
          SELECT FundIDSend
          FROM tbl_FundSubscriptions 
          WHERE FundIDRecv = a.FundIDRecv

      )
      AND UserID = '14'
   )
) as Price
....

答案 1 :(得分:0)

听起来你需要将它重组为JOIN而不是子查询。

答案 2 :(得分:0)

将子查询保留在from子句中并尝试....

试试这个......

 SELECT a.FundIDRecv,a.SubscribeDt, b.FundName, d.price

FROM tbl_FundSubscriptions a, tbl_Hive b,
(  

  SELECT c.PricePerWeek as Price   FROM tbl_Hive c   
   WHERE c.FundID IN  
   (  
      SELECT FundID from tbl_FundStatic
       WHERE FundID IN     
        (
             SELECT FundIDSend
             FROM tbl_FundSubscriptions ,tbl_FundSubscriptions a 
             WHERE FundIDRecv = a.FundIDRecv
        )
        AND UserID = '14' 
 )

 ) d


 WHERE a.FundIDRecv = b.FundID 
 AND a.FundIDRecv IN ( 
 SELECT FundIDRecv FROM   tbl_FundSubscriptions
 WHERE FundIDSend IN 
 (
      SELECT FundID 
      FROM tbl_FundStatic
      WHERE UserID = '14' 
 )
 )
 Group by a.FundIDRecv 

答案 3 :(得分:0)

基本上,我认为是这样的:

SELECT
  a.FundIDRecv,
  a.SubscribeDt,
  b.FundName,
  b.PricePerWeek as Price
FROM tbl_FundSubscriptions a, tbl_Hive b
WHERE a.FundIDRecv = b.FundID
  AND a.FundIDRecv IN (
    SELECT FundIDRecv
    FROM tbl_FundSubscriptions
    WHERE FundIDSend IN (
      SELECT FundID
      FROM tbl_FundStatic 
      WHERE UserID = '14'
    )
  )
Group by a.FundIDRecv, b.PricePerWeek

老式的连接语法我可能会被当前标准的连接语法取代。似乎还有一个冗余的IN子选择。

所以最终脚本可能如下所示:

SELECT
  a.FundIDRecv,
  a.SubscribeDt,
  b.FundName,
  b.PricePerWeek as Price
FROM tbl_FundSubscriptions a
  INNER JOIN tbl_Hive b ON a.FundIDRecv = b.FundID
WHERE a.FundIDSend IN (
  SELECT FundID
  FROM tbl_FundStatic 
  WHERE UserID = '14'
)
Group by a.FundIDRecv, b.PricePerWeek