mySQL:基于用户表单填写首选项的查询

时间:2014-11-18 17:39:07

标签: mysql

答案可能已经在SO中提供了,我正在寻找我的搜索指南(我不知道它是一个案例,还是订购BY ...)

我有一个工作日BD充满了可用的时间表:

+____+__________+________+________+_________+___________+__________+________+
| id | Saturday | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday |
+____+__________+________+________+_________+___________+__________+________+
| 1  |    OFF   |   OFF  |   8-4  |   8-4   |    8-4    |   8-4    |  4-0   |     
| 2  |    4-0   |   OFF  |   OFF  |   8-4   |    8-4    |   8-4    |  8-4   |
| 3  |    4-0   |   OFF  |   OFF  |   8-4   |    8-4    |   8-4    |  4-0   |   
-----------------------------------------------------------------------------

用户将使用优先级填写一种计划偏好形式:

Priority 1: Saturday = OFF  
Priority 2: sunday = OFF  
Priority 3: Monday = 8-4  
Priority 4: Tuesday= 8-4  
Priority 5: Wednesday = 8-4  
Priority 6: Thursday = 8-4  
Priority 7: Friday = 8-4  

现在如果我无法匹配所有7个优先级,我需要检查我是否能够满足他的前6个优先级,如果我不能满足他的前6个我试着去见他的前5个等等,直到我找到一个匹配。

在我们的上述情况中,我无法满足优先级7,因此最佳匹配将是计划ID 1(匹配优先级1到6)。

提前感谢我指出了正确的方向。

1 个答案:

答案 0 :(得分:0)

我会分别运行多个查询。因此,第一个检查所有n个prorities的匹配以及随后检查n-1,n-2 ...优先级。你得到的第一场比赛将是最好的比赛。简化了整体逻辑,性能不会很高

..或者如果你肯定更喜欢一种查询方法,你可以编写一个查询构建循环,它将为你构建类似的东西:

  select 1 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1} AND {Priority2} AND {Priority3} AND{Priority4} AND{Priority5} AND   {Priority6} AND   {Priority7}
UNION
select 2 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1} AND {Priority2} AND {Priority3} AND {Priority4} AND{Priority5} AND   {Priority6} 
UNION
select 3 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1} AND {Priority2} AND {Priority3} AND{Priority4} AND {Priority5} 
UNION
select 4 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1} AND {Priority2} AND {Priority3} AND {Priority4} 
UNION
select 5 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1} AND{Priority2} AND {Priority3}
UNION
select 6 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1} AND{Priority2} 
UNION
select 7 as priority, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM weekdays AS all_priorities WHERE {Priority1}
ORDER BY priority DESC