简体   繁体   English

SQL与自我结合

[英]SQL join with self

I have a table with ID numbers of people and then items of food they've ordered: 我有一张桌子,上面有人的ID号,然后是他们点的食物:

table "food_id" 表“ food_id”

food     id
ham      1
cheese   2
turkey   2
ham      3
ham      4
bread    5
cheese   6
turkey   6
cheese   7

And I'd like to use SQL to figure out, for each id, the total number of other IDs who ordered at least one of the same food items. 我想使用SQL为每个ID找出订购至少一种相同食品的其他ID的总数。 For the above example, the answer should be: 对于以上示例,答案应为:

"result_table" “result_table”

count    id
3        1
3        2
3        3
3        4
1        5
3        6
3        7

The challenge is to avoid double counting here. 面临的挑战是在这里避免重复计算。 For example, person number 2 got both cheese and turkey, so we want his final count to be 3 because person # 2, 6, and 7 got cheese, and person # 2 and 6 got turkey, and there are 3 unique IDs in this list of (2,6,7,2,6). 例如,第2个人获得了奶酪和火鸡,因此我们希望他的最终计数为3,因为第2、6和7个人获得了奶酪,而第2和6个人获得了土耳其,并且在此有3个唯一ID (2,6,7,2,6)的列表。

My initial thoughts were to first get a table with food items to distinct ID numbers, and then to join this table with the original table and then group by ID number and get a count of the distinct number of IDs. 我最初的想法是首先获得一个包含食品的表并具有不同的ID号,然后将该表与原始表连接起来,然后按ID号分组并获得不同ID数的计数。 However, I'm a beginner to SQL and can't figure out how to implement the code correctly. 但是,我是SQL的初学者,无法弄清楚如何正确实现代码。

Any direction would be greatly appreciated. 任何方向将不胜感激。

To avoid the problem with the double counting you can concat both ids from the join and count only distinct combinations. 为了避免重复计数的问题,您可以从连接中合并两个ID,并且仅计数不同的组合。 I add a separator to make the combination unique with greater id values: 我添加了一个分隔符以使组合具有更大的id值唯一:

SELECT 
  COUNT(DISTINCT CONCAT(f1.id, ',', f2.id)) as count,
  f1.id 
FROM
    food_id f1
INNER JOIN
    food_id f2
ON
    f1.food = f2.food
GROUP BY f1.id;

See demo 观看演示

Like you said, you can do a self join. 就像您说的那样,您可以进行自我加入。 You can join by food , and count the number of distinct matching ids. 您可以按food加入,并计算distinct匹配ID的数量。

select
  a.id,  -- Person you're investigating 
  count(distinct b.id) as samefoodcount -- number of people sharing the same food
from
  food_id a
  inner join food_id b on b.food = a.food
group by 
  a.id

Here you can see the query in action: http://sqlfiddle.com/#!2/c53884/1 在这里您可以看到正在使用的查询: http : //sqlfiddle.com/#!2/c53884/1

You can run the following query to get the desired output: 您可以运行以下查询以获取所需的输出:

select MAX(T.total),id
from table_name, (select count(*) as total,food from table_name group by food) T
where table_name.food=T.food
group by id

Check the DEMO 检查演示

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

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