一个查询中有两个计数

时间:2012-10-24 18:49:47

标签: php sql count

我有这张桌子:

id  | id_user  |  id_user_stalkers | date
0   |  0222222 |  032332         | 32234234

所以,我想知道我朋友列表中所有用户的数量,以及让我在他们的朋友列表中的所有用户的cout。 目前,我已经提出了这个问题:

SELECT (
                    SELECT COUNT(id_user)
                    FROM   stalkers WHERE id_user =  ".$id."
                    ) AS user_stalkers,
                    (
                    SELECT COUNT(id_user_stalkers)
                    FROM   stalkers WHERE id_user_stalkers = ".$id."
                    ) AS user_is_stalked
            FROM stalkers  

但它会返回:

Array
(
    [0] => Array
        (
            [user_stalkers] => 7
            [user_is_stalked] => 2
        )

    [1] => Array
        (
            [user_stalkers] => 7
            [user_is_stalked] => 2
        )

    [2] => Array
        (
            [user_stalkers] => 7
            [user_is_stalked] => 2
        )

    [3] => Array
        (
            [user_stalkers] => 7
            [user_is_stalked] => 2
        ))

没关系,但我只需要一行,而不是四行。

有人可以帮帮我吗?

5 个答案:

答案 0 :(得分:1)

由于您的所有字段都是子查询,因此您可以完全删除from子句。否则,您将获得表中每一行的子查询。这不仅可以获得您想要的结果,还可以通过潜在的非常大量(提高性能)来降低数据库的总命中率。

SELECT 
(
 SELECT COUNT(id_user)
 FROM   stalkers WHERE id_user =  ".$id."
) AS user_stalkers,
(
 SELECT COUNT(id_user_stalkers)
 FROM   stalkers WHERE id_user_stalkers = ".$id."
) AS user_is_stalked

如果这将是一个可能很大的表,您需要确保id_user和id_user_stalkers都被编入索引。如果可以使用索引,这些子查询将会快得多。

答案 1 :(得分:0)

你必须再添加一个where子句,如下所示:

SELECT DISTINCT (
                    SELECT COUNT(id_user)
                    FROM   stalkers WHERE id_user =  ".$id."
                    ) AS user_stalkers,
                    (
                    SELECT COUNT(id_user_stalkers)
                    FROM   stalkers WHERE id_user_stalkers = ".$id."
                    ) AS user_is_stalked
FROM stalkers  
WHERE id_user_stalkers = ".$id."

答案 2 :(得分:0)

为任何数据库设置此查询的安全方法是使用cross join

SELECT user_stalkers, user_is_stalked
from (SELECT COUNT(id_user) as user_stalkers
      FROM   stalkers WHERE id_user =  ".$id."
     ) t1 cross join
     (SELECT COUNT(id_user_stalkers) as user_is_stalked
      FROM   stalkers WHERE id_user_stalkers = ".$id."
     )  t2

由于Stalkers子句,您的查询为FROM中的每一行返回一行。

答案 3 :(得分:0)

         SELECT (
                SELECT COUNT(id_user)
                FROM   stalkers WHERE id_user =  ".$id."
                ) AS user_stalkers,
                (
                SELECT COUNT(id_user_stalkers)
                FROM   stalkers WHERE id_user_stalkers = ".$id."
                ) AS user_is_stalked

删除最后一个“FROM stalkers”

答案 4 :(得分:0)

试试这个(你不必再查询两次并担心不同等)

SELECT COUNT(case when id_user =  ".$id." then 1 else null) AS user_stalkers,
COUNT(case when id_user_stalkers =  ".$id." then 1 else null) AS user_is_stalked
FROM   stalkers