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