1

我试图计算表中的行数。目前我正在使用这个:

$sql = "SELECT COUNT(*) 
        FROM `friends` 
        WHERE `user1`='".$user1."' 
            AND `user2`='".$user2."' 
            AND `valid`=0 
        UNION 
        SELECT COUNT(*) 
        FROM `friends` 
        WHERE `user1`='".$user2."' 
            AND `user2`='".$user1."' 
            AND `valid`=0";

如您所见,user1可以同时是$user1AND $user2。但它不计算 之后的行UNION,它只执行之前的第一个查询,UNION所以当我实际上应该计算 1 行时,我以 0 结束。

我该如何解决这个问题?

4

4 回答 4

4

另一种选择,将您的查询替换为:

$sql = "SELECT COUNT(*) 
    FROM `friends` 
    WHERE (
            (`user1`='".$user1."' AND `user2`='".$user2."') OR
            (`user1`='".$user2."' AND `user2`='".$user1."')
          )
     AND `valid`=0";
于 2012-07-11T17:24:38.467 回答
2

您的查询实际上返回 2 条记录 -0第一个计数和1第二个计数。您可以对结果使用子查询SUM()...

$sql = "SELECT SUM(A) AS COUNT FROM
(SELECT COUNT(*) AS A
        FROM `friends` 
        WHERE `user1`='".$user1."' 
            AND `user2`='".$user2."' 
            AND `valid`=0 
        UNION 
        SELECT COUNT(*) 
        FROM `friends` 
        WHERE `user1`='".$user2."' 
            AND `user2`='".$user1."' 
            AND `valid`=0
)";
于 2012-07-11T17:25:25.440 回答
1

改为使用UNION ALLUNION将排除重复的行。

于 2012-07-11T17:22:24.560 回答
1

您可以使用更简单的解决方案:

SELECT COUNT(*)
FROM friends
WHERE 
    $user1 IN (user1,user2) AND 
    $user2 IN (user1,user2) AND
    valid = 0
于 2012-07-11T17:31:40.627 回答