Mysql查找所有用户的常用值

时间:2018-05-17 11:16:17

标签: mysql

我们正在开发一个本地商店推荐系统,在我们的一个SQL查询中,我们遇到了问题 我们想要获取同一集群中所有用户评级的公司,但如果同一组中的任何一个用户没有评价该公司我们不想获取它

SELECT ml_user_clusters.primaryUser,ml_user_clusters.clusterId,ml_ratings.companyId,ml_ratings.rating,ml_user_labels.groupId FROM ml_user_clusters 
LEFT JOIN ml_ratings ON  ml_ratings.userId = ml_user_clusters.primaryUser
LEFT JOIN ml_company_user_labels ON ml_company_user_labels.companyId = ml_ratings.companyId 
LEFT JOIN ml_user_labels ON ml_user_labels.groupId = ml_company_user_labels.labelId 
WHERE ml_user_clusters.clusterId = 0

我们已经开始添加如下所示的查询,但无法使用正确的AND子句完成它

我们的数据如下所示:因此,在结果中,我们希望只有groupId = 6的公司,因为同一群集中的所有用户(clusterId = 0)对groupId = 6的公司进行评级

primaryUser clusterId   companyId   rating  groupId
497 0   135 5   NULL
498 0   135 10  NULL
79  0   135 12  NULL
501 0   135 10  NULL
79  0   85  14  2
79  0   8   4   5
79  0   98  11  5
79  0   3   5   5
497 0   6   7   6
500 0   6   7   6
499 0   29  7   6
497 0   29  7   6
499 0   77  7   6
500 0   29  7   6
498 0   6   7   6
500 0   77  11  6
500 0   130 3   6
498 0   130 3   6
501 0   77  19  6
499 0   6   7   6
79  0   30  1   7
500 0   30  7   7
79  0   48  7   9
79  0   39  1   13
79  0   48  7   13
499 0   6   7   15
497 0   6   7   15
79  0   8   4   15
500 0   6   7   15
79  0   98  11  15
498 0   6   7   15
79  0   3   5   15
79  0   81  7   15
79  0   3   5   17
79  0   82  7   17
79  0   103 7   17
79  0   118 3   17
79  0   63  3   17
501 0   118 7   17
79  0   82  7   19
79  0   118 3   19
79  0   63  3   19
501 0   118 7   19
79  0   39  1   21
79  0   85  14  23

预期输出必须为:(因为Cluster = 0中的所有唯一身份用户都评定了GroupID = 6的公司)

primaryUser clusterId   companyId   rating  groupId

497 0   6   7   6
500 0   6   7   6
499 0   29  7   6
497 0   29  7   6
499 0   77  7   6
500 0   29  7   6
498 0   6   7   6
500 0   77  11  6
500 0   130 3   6
498 0   130 3   6
501 0   77  19  6
499 0   6   7   6

你知道我们如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这样的事情应该有用,你应该建立一个小提琴,以便更好地进行测试。

说明:您计算按组ID分组的不同用户,并与不同用户的总数进行比较。如果两者匹配则表示该相应groupid中的所有用户都已投票。

SELECT ml_user_labels.groupId
FROM ml_user_clusters
LEFT JOIN ml_ratings ON ml_ratings.userId = ml_user_clusters.primaryUser
LEFT JOIN ml_company_user_labels ON ml_company_user_labels.companyId = ml_ratings.companyId
LEFT JOIN ml_user_labels ON ml_user_labels.groupId = ml_company_user_labels.labelId
WHERE ml_user_clusters.clusterId = 0
GROUP BY ml_user_labels.groupId
HAVING COUNT(DISTINCT ml_user_clusters.primaryUser) =
  (SELECT COUNT(DISTINCT ml_user_clusters.primaryUser)
   FROM ml_user_clusters
   LEFT JOIN ml_ratings ON ml_ratings.userId = ml_user_clusters.primaryUser
   LEFT JOIN ml_company_user_labels ON ml_company_user_labels.companyId = ml_ratings.companyId
   LEFT JOIN ml_user_labels ON ml_user_labels.groupId = ml_company_user_labels.labelId
   WHERE ml_user_clusters.clusterId = 0)x