MariaDB:带连接的复杂查询

时间:2016-06-08 12:07:42

标签: mysql mariadb

我试图让所有拥有多件衣服的用户获得正确的结果

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

有什么想法吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

由于您已经两次加入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;

答案 2 :(得分:1)

您可以大大简化查询。您实际上并不需要任何join,只需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) > 1count(distinct)通常是一项更昂贵的操作。比较最小值和最大值也是一样的。