如何根据列名对结果进行排序?

时间:2015-11-18 16:59:13

标签: php mysql regex sql-order-by

如何创建智能搜索查询取决于列名?

我有一张这样的表:

+----+----------+-------+-------+
| id |   name   | code1 | code2 |
+----+----------+-------+-------+
| 1  |  jack    | 1     | 1     |
| 2  |  peter   | 1     | 2     |
| 3  |  abel    | 1     | 3     |
| 4  |  brent   | 2     | 1     |
| 5  |  arnold  | 2     | 2     |
| 6  |  chester | 3     | 1     |
| 7  |  morgan  | 3     | 2     |
| 8  |  olin    | 3     | 3     |
| 9  |  marvin  | 3     | 4     |
| 10 |  gavin   | 3     | 5     |
| 11 |  harley  | 4     | 1     |
+----+----------+-------+-------+

好吧,我有 3个关键字: namecode1code2

我的问题是关于结果的顺序取决于那些关键字。有一些例子:

例1:

$q = 'name brent'; // it is what user writes for search in the input
                   // actually I meant of smart is detecting this automatically:
                   // keyword: 'name', value: 'brent'

我想要这个输出:

+----+----------+-------+-------+
| 4  |  brent   | 2     | 1     |
|                               |
| /* the order of other colunms |
|    does not matter */         |
|                               |
+----+----------+-------+-------+

例2:

$q = 'code1 3';

我想要这个输出:

+----+----------+-------+-------+
| 6  |  chester | 3     | 1     |
| 7  |  morgan  | 3     | 2     |
| 8  |  olin    | 3     | 3     |
| 9  |  marvin  | 3     | 4     |
| 10 |  gavin   | 3     | 5     |
|                               |
| /* the order of other colunms |
|    does not matter */         |
|                               |
+----+----------+-------+-------+

示例3:

$q = 'code1 3 code2 2';

我想要这个输出:

+----+----------+-------+-------+
| 7  |  morgan  | 3     | 2     |
|                               |
| /* the order of other colunms |
|    does not matter */         |
|                               |
+----+----------+-------+-------+

示例4 :如果输入中有三个关键字,则code1code2具有更高的优先级。

$q = 'name jack code1 3 code2 1';

我想要这个输出:

+----+----------+-------+-------+
| 6  |  chester | 3     | 1     |    // code1 3 code2 1
| 1  |  jack    | 1     | 1     |    // name jack
|                               |
| /* the order of other colunms |
|    does not matter */         |
|                               |
+----+----------+-------+-------+

示例5:如果关键字(name jack =>关键字:name的值,值:jack)不存在,则表示:关键字及其值不会被考虑,就像它在输入中不存在一样。

$q = 'code1 2 code2 5';

我想要这个输出:

+----+----------+-------+-------+
| 4  |  brent   | 2     | 1     |
| 5  |  arnold  | 2     | 2     |
|                               |
| /* the order of other colunms |
|    does not matter */         |
|                               |
+----+----------+-------+-------+

首先,我想我必须分开字符串的数字,如下所示:

preg_match_all('!\d+!u', $q, $matches);

然后在我的查询中使用它们,如下所示:

... IN (" .implode(',', $matches[0]) . ") ...

或者我不知道,有什么好的解决方案吗?实际上我需要的是一个神奇的命令......!

0 个答案:

没有答案