COUNT有两列,每列都有自己的AS值

时间:2016-11-18 06:03:34

标签: mysql sql

我在查询中尝试COUNT两个不同的值,我需要分配两个不同的AS值,因为这些值是分开的。

我尝试添加+以及AND来实现此功能。我不确定还能做什么,而且我再也不能将friend_onefriend_two加在一起。

有什么想法吗?

SELECT *, COUNT(friend_one) AS pending_count + COUNT(friend_two) AS requests_sent
FROM friends
WHERE friend_one OR friend_two = ?
AND status = ?

3 个答案:

答案 0 :(得分:0)

Plz尝试这样的事情:

SELECT SUM(friend_one = $myID) AS pending_count,
   SUM(friend_two = $myID) AS pending_count
FROM friends
WHERE friend_one = $myID
   OR friend_two = $myID

答案 1 :(得分:0)

尝试以下查询

 SELECT *, (COUNT(friend_one) + COUNT(friend_two)) AS pending_count_And_requests_sent
FROM friends
WHERE friend_one OR friend_two = ?
AND status = ?

答案 2 :(得分:0)

您需要子查询来访问计数列并添加它们

SELECT *,pending_count1 + pending_count2 As request_sent
FROM
(
SELECT *, COUNT(friend_one) AS pending_count1 , COUNT(friend_two) AS pending_count2
FROM friends
WHERE friend_one OR friend_two = ?
AND status = ?
) As Tmp

这给了来自朋友表的所有列以及freind ane和freind 2的计数以及它们的总和作为request_sent