3

我有 2 个 mysql 表,一个称为“用户”,另一个称为“连接”

表用户有关于用户的信息,并且有 3 行:

mikha
guy
maricela

表连接有 twitter 等用户之间的连接(例如 mikha 关注 maricela 和 maricela 关注 mikha)

Connections 具有以下行:

username1     | username2
--------------------------
guy           | maricela
mikha         | guy
mikha         | maricela

我想获取有关“mikha”的信息,包括他关注的人数和关注他的人数。

我使用以下查询:

SELECT *, COUNT(DISTINCT  connections.username1) AS count_following, 
   COUNT(DISTINCT connections.username2)  AS count_followers 
FROM users LEFT JOIN connections on connections.username1 = 'mikha' OR  
   connections.username2 = 'mikha' WHERE users.username = 'mikha'

预期的:

count_following = 2 (as mikha is following guy and maricela)
count_followers = 0 (no one following mikha yet)

实际的:

count_following = 2
count_followers = 1

谢谢问候迈克尔

4

1 回答 1

1

您可以运行两个不同的查询(fiddle here):

select
  (select count(*) from connections
  where username1 = 'mikha') following,
  (select count(*) from connections
  where username2 = 'mikha') followers

或者只是使用这个(小提琴here):

select
    sum(username1 = 'mikha') following,
    sum(username2 = 'mikha') followers
from connections

我认为第二个应该更快。一旦你得到它,只需加入你的用户表,以防你需要来自该表的额外信息(根据你的例子,你不需要)。

于 2012-11-24T00:44:36.447 回答