SQL查找所有同源类别

时间:2016-09-23 13:26:06

标签: mysql sql cross-join

我在Category和Item之间有多对多的关系,这是用" category_item"表,有2列(PK):category_iditem_id

两个同源类别具有相同的项目(顺序不相关):

A
  1
  2

同源
B
  1
  2

但不是

C       D       E
  1       1       1
  3               2
                  3

鉴于类别ID,我如何找到所有同源类别?

假设item_category中的这些数据:

A   1
A   2
B   1
B   2
C   1
C   3
D   1
E   1
E   2
E   3

我想找到与A同源的所有类别(预期结果只是B

我目前正在尝试这样的事情:

select r2.category_id
from category_item r1, category_item r2
where r1.category_id = ?
    and r2.category_id <> r1.category_id
    and r1.item_id = r2.item_id

构建表:

A   1   B   1
A   1   C   1
A   1   D   1
A   1   E   1
A   2   B   2
A   2   D   2
A   2   E   2

但我不知道如何继续......

我使用的是MySQL 5.7,但我只想使用通用SQL。

请注意,这不是作业(我也不认为任何教师会分配这么复杂的作业),它只是一个现实世界问题的简化用例< / em>的

2 个答案:

答案 0 :(得分:2)

为什么不使用Group_Concat()然后分组?

select ColA, group_concat(ColB order by ColB separator '|') as concat_line
from CategoryItem
group by ColA

如果你将它停放在某个地方,你可以将它与自身进行比较。

答案 1 :(得分:1)

您也可以使用子查询和exists / not exists

来执行此操作
Select Distinct category_id 
from category_item ci
Where not exists   -- this allows only cats that do not have all req items
      (select * from category_item
       Where category_id = ci.category_id 
         and item_id Not in 
            (Select item_id from category_item
             Where category_Id = @catId))
  and not exists   -- this filters out cats that have xtra items
      (Select * from category_item
       Where category_Id = @catId
          and item_id Not in
            (Select item_id from category_item
             Where category_Id = ci.category_Id )) 
  and category_Id <> @catId -- <- categoryId of category you are matching
                            -- this line filters out the category you are 
                            -- matching against. Remove it if you want all
                            -- homologous categories

说明:

Select All distinct {CATEGORY_ID {1}} {ITEM_ID {1}} {ITEM_ID {1}}