简体   繁体   English

如何在SQL查询中创建配对?

[英]How to create pairs in sql query?

Could anyone tell me how to create pairs in MySQL. 谁能告诉我如何在MySQL中创建配对。 If you see the below query 如果您看到以下查询

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'

Could anyone tell me how can I create pairs of Cakeid which uses atleast three common ingredient ? 谁能告诉我如何创建使用至少三种常见成分的Cakeid对? For example, 6 and 7 are one pair which have three common ingredient. 例如,6和7是一对,具有三个共同的成分。

Self-join 自我加入

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

The query below will give you the cakeids next to each other that contain more than 3 common ingredients. 下面的查询将为您提供包含3种以上常用成分的Cakeids。

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

To get the list you wanted from this, you need to join the above query once on the cakeid1, and once on the cakeid2 to the contain table again: 要从中获得所需的列表,您需要在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

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

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