将2个表与通配符进行比较

时间:2011-11-21 18:52:19

标签: php mysql wildcard

我需要比较2个表,其中一个表有数据,另一个表有解释。

因此数据表如下所示:

id  | state | substate | stage | suppressed
001    wip     A1          B3        Y
003    wip     A1          B1        N
005    done    A2          B3        Y
009    wip     A1          B3        N
... and many more similar

解释表必须得到上面的4个状态(状态,子状态,阶段,抑制)并将它们翻译成人类可读的状态:

state | substate | stage | suppressed | HRoutput1     | HRoutput2
wip        A1        B1        N        "it's ok"       "wait...dont do anything"
wip        A1        B3        N        "it's not ok"   "better call saul"
done       A2        B3        Y        "it's not ok"   "forget about it"
wip        A1        B1        Y        "it's ok"       "something minor needs to be done"
*          *         *         Y        "it's ok"       "it's suppressed"
done       *         *         *        "it's ok"       "it's being worked on"

现在看到上面的解释表有2个阶段,我在表中使用了通配符

*,*,*,Y,"it's ok","its suppressed"

当state,substate,stage和suppress在上述任何条件中都不匹配时,应使用此选项。

到目前为止,我将数据的每一行加载到数组A中 然后让元素数组A遍历解释表:

 "SELECT * from explanation_table where state = '" . $data['state'] ."' and '" . $data['substate'] . "' ....etc etc

然后运行查询并将结果保存到解释数组中并打印结果

 $data['id'] .  $expl['HRoutput1'] .  $expl['HRoutput2']

除了带有通配符的情况外,我的代码工作正常。

1 个答案:

答案 0 :(得分:1)

要从查询中恢复,您可以执行以下操作:

"SELECT * from explanation_table where (state = '" . $data['state'] ."' OR state = '*') and (substate = '" . $data['substate'] . "' OR substate = '*') ....etc etc.... ORDER BY state != '*', substate != '*' ... LIMIT 1

这样,您将匹配通配符和精确的state / substate / ...匹配,将实际匹配值高于通配符匹配(order by)并仅返回最佳匹配结果。