1

我有这张桌子:

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

所以,我想知道我的朋友列表中所有用户的数量,以及我在他们的朋友列表中的所有用户的数量。目前,我做了这个查询:

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
        ))

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

有人可以帮我吗?

4

5 回答 5

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 都被索引。如果可以使用索引,这些子查询将快得多。

于 2012-10-24T18:55:37.120 回答
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."
于 2012-10-24T18:53:43.267 回答
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子句,您的查询为每一行返回一行。

于 2012-10-24T18:54:29.567 回答
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”

于 2012-10-24T18:54:31.427 回答
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
于 2012-10-24T18:59:06.087 回答