【问题标题】:MYSQL join duplicate results even with DISTINCT即使使用 DISTINCT,MYSQL 也会加入重复的结果
【发布时间】:2012-11-12 07:11:46
【问题描述】:

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

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

mikha
guy
maricela

Table connections 有 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

谢谢 问候 迈克尔

【问题讨论】:

    标签: php mysql database join duplicates


    【解决方案1】:

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

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

    或者直接使用这个 (fiddle here):

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2012-11-04
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多