简体   繁体   English

带计数的交叉联接MySQL查询

[英]Cross Join MySQL Query with Counts

I need some help with a MySQL query. 我需要有关MySQL查询的帮助。 I have a table with two columns (usr_id and search_term) and with the following data. 我有一个包含两列(usr_id和search_term)并具有以下数据的表。

1 term1 1学期1
1 term2 1学期2
2 term1 2学期1
2 term2 2学期2
2 term3 2学期3
3 term2 3学期2
3 term3 3学期3
4 term1 4学期1
4 term3 4学期3

I need to be write a query to generate the a list of all the possible combinations of terms and report the total number of usr_id's where the combination occurs. 我需要编写一个查询来生成所有可能的术语组合的列表,并报告发生组合的usr_id的总数。

term1 term2 2 term1 term2 2
term1 term3 1 term1 term3 1
term2 term3 1 term2 term3 1

If I understand correctly, you want to count the number users that have any given pair of terms. 如果我理解正确,则需要计算具有给定术语对的用户数。 You have to be careful about not overcounting if a user uses a term more than once. 如果用户多次使用术语,则必须小心不要过度计算。

select t1.term as term1, t2.term as term2,
       count(distinct t1.usr_id) as num_users
from table t1 join
     table t2
     on t1.usr_id = t2.usr_id and t1.term <> t2.term
group by t1.term, t2.term;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM