0

我正在使用 Ruby on Rails v3.2.2 和 MySQL 数据库。我有一个包含数据的数据库表,如下所示(注意:column1包含逗号分隔的字符串):

id   | column1                          | column2 | columnM    
-----|-----------------------------------------------------
1    | one1                             | value1  |  ...
2    | one1, two1                       | value1  |  ...
3    | one1, two1, three1               | value1  |  ...
4    | one2                             | value2  |  ...
5    | one2, two2                       | value2  |  ...
6    | one2, two2, three2               | value2  |  ...
...  | ...                              | ...     |  ...
1000 | oneN                             | valueN  |  ...
1001 | oneN, twoN                       | valueN  |  ...
1002 | oneN, twoN, threeN               | valueN  |  ...
1003 | oneN, twoN, threeN, fourN        | valueN  |  ...

我想编写一个 SQL 查询,以便检索同时column1. 也就是说,例如,假设我column1搜索字符串

Case 1: "thr"
Case 2: "two1 thr"
Case 3: "two thr"
Case 4: "wo"
Case 5: "one"
Case 6: "four one"

然后,我想分别获取以下记录id

Case 1: 3, 6, 1002, 1003                         # returns all records starting with "thr"
Case 2: 3                                        # returns all records starting with "two1" and at the same time starting with "thr" 
Case 3: 3, 6, 1002, 1003                         # returns all records starting with "two" and at the same time starting with "thr"
Case 4:                                          # nothing to return
Case 5: 1, 2, 3, 4, 5, 6, 1000, 1001, 1002, 1003 # returns all records starting with "one"
Case 6: 1003                                     # returns all records starting with "four" and at the same time starting with "one"

我怎样才能使 SQL 查询表现得像上面那样(也许,通过使用通配符或其他我不知道的东西)由于我正在尝试实现一个“简单”的搜索引擎,你有什么建议?有一些处方吗?

4

1 回答 1

0

看LIKE子句,即案例2:

SELECT *
  FROM TBL
 WHERE 1
   AND CONCAT(', ', column1) LIKE '%, two1%'
   AND CONCAT(', ', column1) LIKE '%, thr%'

这里的技巧是您要确保要搜索的字符串是逗号分隔项之一的开头,因此是前导,(逗号空格)。第一项不存在,因此我们CONCAT()将其转到列,转向one, two1=> , one, two1。LIKE 模式可以正常工作。

WHERE 1是一种用一个条件“使用”种子 WHERE 子句的模式,因此对于您需要搜索的每个单词,您可以添加一个AND表达式

   AND CONCAT(', ', column1) LIKE '%, someword%'
于 2012-11-07T18:11:15.510 回答