【问题标题】:MariaDB: Complex query with joinMariaDB:带连接的复杂查询
【发布时间】:2016-06-08 12:07:41
【问题描述】:

我试图让所有拥有不止一件衣服但没有得到正确结果的用户

select us.id from users as us
                        inner join user_clothes as uc1 ON (uc1.userId = us.id)
                        inner join clothes as cl on (cl.id = uc1.clothesId)
                        inner join user_clothes as uc2 on (cl.id = uc2.clothesId)
                        HAVING COUNT(uc2.clothesId) > 0

有什么想法吗?

【问题讨论】:

  • 添加GROUP BY us.id开始
  • 谢谢,@AgRizzo。这确实是一个好的开始。 GROUP BY us.id 不起作用,但 GROUP BY uc2.clothesId 确实起作用。 :)
  • 我怀疑你没有从 clothesID 分组中得到正确的结果,反正看起来很奇怪

标签: mysql mariadb


【解决方案1】:

您似乎对 user_clothes 进行了不必要的连接,并且您缺少 GROUP BY 子句,所以:

select us.id from users as us
inner join user_clothes as uc1 ON (uc1.userId = us.id)
inner join clothes as cl on (cl.id = uc1.clothesId)
GROUP BY us.id
HAVING COUNT(distinct uc1.clothesId) > 0

【讨论】:

    【解决方案2】:

    由于您已加入 user_clothes 表两次,该表中的每条记录将被计算两次。虽然你可以这样做:

    select us.id from users as us
        inner join user_clothes as uc1 
          ON (uc1.userId = us.id)
        inner join user_clothes as uc2 
          ON (uc2.userId = us.id
              AND uc2.clothesId<>uc1.clothesId)
    

    这种方法不能很好地回答其他问题(正好 2 件衣服,超过 5 件衣服......)因此......

      SELECT us.id
      FROM users AS us
      INNER JOIN join user_clothes as uc 
         ON (uc.userId = us.id)
      GROUP BY us.id
      HAVING COUNT(DISTINCT uc.clothesId)>1;
    

    【讨论】:

      【解决方案3】:

      您可以大大简化您的查询。你实际上不需要任何joins,只需要group by

      select uc.userId
      from user_clothes uc
      group by uc.userId
      having min(uc.clothesId) <> max(uc.clothesId);
      

      此查询所需的所有信息都在user_clothes 表中。

      注意:您也可以使用having count(distinct uc.clothesId) &gt; 1count(distinct) 通常是更昂贵的操作。比较最小值和最大值的作用相同。

      【讨论】:

      • 我觉得应该是uc.userID
      猜你喜欢
      • 2020-03-31
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多