如何在SQL查询中创建对?

时间:2015-10-13 08:32:51

标签: mysql

有人能告诉我如何在MySQL中创建对。如果您看到以下查询

select A.cakeid , A.ingredid from Contain as A inner join (select 
    cakeid, count(cakeid)
from
    Contain
group by cakeid
having count(cakeid) >= 3 ) as B on A.cakeid = B.cakeid 

OUTPUT:

Cakeid Ingredid
'1', '1'
'1', '3'
'1', '4'
'3', '1'
'3', '4'
'3', '5'
'5', '1'
'5', '2'
'5', '4'
'6', '1'
'6', '2'
'6', '3'
'6', '5'
'7', '1'
'7', '2'
'7', '3'
'7', '4'
'8', '1'
'8', '2'
'8', '3'

有谁能告诉我怎样才能创建使用至少三种常见成分的Cakeid对?例如,6和7是一对具有三种常见成分。

2 个答案:

答案 0 :(得分:3)

自加入

select c1.cakeid cake1, c2.cakeid cake2, count(*) matching_Ingredid  
from Contain c1
join Contain c2 
    on c1.cakeid < c2.cakeid and c1.Ingredid = c2.Ingredid
group by c1.cakeid, c2.cakeid
having count(*) >= 3

答案 1 :(得分:1)

下面的查询将为您提供彼此相邻的含有3种以上常见成分的蛋糕。

select c1.cakeid as cakeid1, c2.cakeid as cakeid2 from
contain c1 inner join contain c2 on c1.ingredid=c2.ingredid and c1.cakeid<c2.cakeid
group by c1.cakeid, c2.cakeid
having count(*)>=3

要从中获取您想要的列表,您需要在cakeid1上加入上述查询一次,并在cakeid2上再次加入到包含表格中:

select c3.cakeid, c3.ingredid from content c3 inner join
(select c1.cakeid as cakeid1, c2.cakeid as cakeid2 from
contain c1 inner join contain c2 on c1.ingredid=c2.ingredid and c1.cakeid<c2.cakeid
group by c1.cakeid, c2.cakeid
having count(*)>=3) t1 on c3.cakeid=t1.cakeid1
union all
select c4.cakeid, c4.ingredid from content c4 inner join
(select c1.cakeid as cakeid1, c2.cakeid as cakeid2 from
contain c1 inner join contain c2 on c1.ingredid=c2.ingredid and c1.cakeid<c2.cakeid
group by c1.cakeid, c2.cakeid
having count(*)>=3) t2 on c4.cakeid=t2.cakeid2