MariaDB:带连接的复杂查询

MariaDB: Complex query with join

我正在尝试获取所有拥有不止一件衣服但未获得正确结果的用户

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

有什么想法吗?

您似乎对 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

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

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;

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

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

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

注意:您也可以使用having count(distinct uc.clothesId) > 1count(distinct) 通常是一个更昂贵的操作。比较最小值和最大值做同样的事情。