您好我有一个查询,它返回两行数据作为计数。我想找到列值的总和。我的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(我的上面的查询)但是我收到了错误。有人可以帮帮我吗。我只需要一些上述值。
此致 的Pankaj
答案 0 :(得分:4)
可以在一个查询中抓取两个结果集:
SELECT count(memberid) count
FROM `friendRequest`, Member
WHERE status = 2 AND (
(memberid = sender AND receiver = 19) OR
(memderid = receiver AND sender = 19)
)
答案 1 :(得分:0)
尝试:
SELECT SUM(count)
FROM
...the rest of your query...
答案 2 :(得分: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)
答案 3 :(得分: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