MySQL根据偏好匹配两个用户

时间:2018-06-25 04:08:19

标签: mysql stored-procedures mariadb

好的,我需要完成的工作有点复杂,但是我会尽力解释。 所以我有一个这样的表:

  

id ||颜色|| redOK || blueOK || yellowOK || greenOK ||橙色确定

     

1- || ---- 1 --- || ---- 1 ----- || ----- 1 ----- || ------- 1 ------ || ------ 0 ------ ||| ------ 1 ------

     

2- || ---- 3 --- || ---- 1 ----- || ----- 0 ----- || ------- 1 ------ || ------ 1 ------ || ------ 1 ------

     

3- || ---- 1 --- || ---- 0 ----- || ----- 0 ----- || ------- 0 ------ || ------ 0 ------ ||| ------ 1 ------

     

4- || ---- 5 --- || ---- 1 ----- || ----- 1 ----- || ------- 0 ------ || ------ 1 ------ || ------ 1 ------

     

5- || ---- 2 --- || ---- 0 ----- || ----- 0 ----- || ------- 1 ------ || ------ 0 ------ ||| ------ 1 ------

在颜色字段中,数字1-5代表用户喜欢的颜色(1代表红色,2代表蓝色,3代表黄色,4代表绿色和5代表橙色)。 redOK,blueOk,yellowOK,greenOK和orangeOK字段表示用户是否愿意与具有特定喜欢颜色的某人进行匹配。在这些字段中,1表示是,0表示否。因此,例如,id = 1的用户喜欢的颜色是红色,因为他们的“颜色”字段为1,他们愿意与用户喜欢的颜色是红色,蓝色,黄色或橙色,但不喜欢绿色的人匹配,因为“ greenOK”字段为0。因此,我需要做的是创建一个存储过程,该存储过程返回其颜色和颜色首选项与特定用户的颜色和颜色首选项匹配的用户的查询。因此,例如,id为1和2的用户将是一个匹配项,因为用户1为红色,用户2选择红色为好,用户2为黄色,用户1选择黄色为好。另一方面,用户3和2不会匹配,因为即使用户3是红色,并且用户2选择红色是可以的,用户2是黄色,用户3则说只有橙色是可以的。

我整天都在考虑这个问题,但还不能完全解决。我的第一个想法是使用SELECT INNER JOIN语句,但是由于存在太多可能的组合,我不确定如何做到这一点?然后,我尝试使用用户的首选项创建一个临时表,然后使用游标在这些首选项之间进行迭代,同时检查用户的首选项是否与目标用户的颜色匹配,但我也无法弄清楚。你们可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

按原样使用表,只有五种组合决定了一个匹配,您可以简单地在一个连接中对a-> b和a <-b两个方向进行或运算或组合:

select *
from myTable a
join myTable b on (
        (a.color = 1 and b.redOK = 1)
        or (a.color = 2 and b.blueOK = 1)
        or (a.color = 3 and b.yellowOK = 1)
        or (a.color = 4 and b.greenOK = 1)
        or (a.color = 5 and b.orangeOK = 1)
    ) and (
        (b.color = 1 and a.redOK = 1)
        or (b.color = 2 and a.blueOK = 1)
        or (b.color = 3 and a.yellowOK = 1)
        or (b.color = 4 and a.greenOK = 1)
        or (b.color = 5 and a.orangeOK = 1)
    )
where a.id <> b.id

或者,您可以更改架构,从根本上将数据移到多对多表中。例如:

id    okColor
1     1
1     2
1     3
1     5
2     1
2     3
2     4
2     5

在这种情况下,您可以通过此表进行联接:

select distinct a.id, b.id
from myTable a
join okColors aOK on a.id = aOK.id
join myTable b on aOK.okColor = b.color
join okColors bOK on bOK.id = b.id and a.color = bOK.okColor
where a.id <> b.id
相关问题