0

我有一个查询,它返回两行数据作为计数。我想找到列值的总和。我的 sql:

(SELECT count(memberid) count 
   FROM `friendRequest`, Member 
   where status = 2 and memberid = sender and receiver = 19) 
UNION 
(SELECT count(memberid) count 
   FROM `friendRequest`, Member 
   where status = 2 and memberid = receiver and sender = 19)

我试过使用Select Sum(my above query),但我收到错误。我只需要上面的一些值。

4

4 回答 4

4

可以在单个查询中获取两个结果集:

SELECT count(memberid) count 
FROM `friendRequest`, Member 
WHERE status = 2 AND (
    (memberid = sender AND receiver = 19) OR 
    (memderid = receiver AND sender = 19)
)
于 2012-06-14T19:28:05.390 回答
0

尝试:

SELECT SUM(count)
FROM
  ...the rest of your query...
于 2012-06-14T19:20:47.540 回答
0

如果要使用聚合,则需要使用以下内容对其进行分组GROUP BY

(SELECT count(memberid) SUM(count) 
   FROM `friendRequest`, Member 
   where status = 2 and memberid = sender and receiver = 19
   GROUP BY Member) 
UNION 
(SELECT count(memberid) SUM(count) 
   FROM `friendRequest`, Member 
   where status = 2 and memberid = receiver and sender = 19
   GROUP BY Member)
于 2012-06-14T19:30:15.510 回答
0

以下应该按原样工作

SELECT SUM(count)
FROM   (
         (SELECT count(memberid) count 
          FROM `friendRequest`, Member 
          where status = 2 and memberid = sender and receiver = 19) 
          UNION 
         (SELECT count(memberid) count 
          FROM `friendRequest`, Member 
          where status = 2 and memberid = receiver and sender = 19)
       ) AS anyAliasWillDo

但我强烈建议您停止使用隐式连接(已过时)并开始使用显式连接语法。然后声明变成

SELECT SUM(COUNT)
FROM   (
            SELECT  COUNT(memberid) AS COUNT 
            FROM    `friendRequest` AS fr
                    INNER JOIN Member AS m ON m.memberid = fr.sender
            WHERE   status = 2 AND receiver = 19 
            UNION ALL
            SELECT  COUNT(memberid) AS COUNT 
            FROM   `friendRequest` AS fr 
                    INNER JOIN Member AS m ON m.memberid = fr.receiver
            WHERE   status = 2 AND sender = 19
        ) AS AnyAliasWillDo
于 2012-06-14T19:30:23.463 回答