mysql里做字符的最佳匹配_MySQL,选择至少匹配X个字符的记录

好吧,这有点丑陋,但确实可以正常工作.它是通用的SQL,可以在任何环境中使用.只需生成一个大于您正在读取的字段的最大长度的子字符串选择项即可.将函数中的数字50更改为超出字段长度的数字.它可能会返回一个很长的查询,但是就像我说的那样,它将很好地工作.这是Python中的示例:

import sqlite3

c = sqlite3.connect('test.db')

c.execute('create table myTable (id integer, content varchar[50])')

for id, content in ((1,'apple'),(2,'pineapple'),(3,'application'),(4,'nation')):

c.execute('insert into myTable values (?,?)', [id,content])

c.commit();

def GenerateSQL(substrSize):

subqueries = ["select substr(content,%i,%i) AS substr, count(*) AS myCount from myTable where length(substr(content,%i,%i))=%i group by substr(content,%i,%i) " % (i,substrSize,i,substrSize,substrSize,i,substrSize) for i in range(50)]

sql = 'select substr FROM

(' + '

union all '.join(subqueries) + ')

GROUP BY substr HAVING sum(myCount) > 1'

return sql

print GenerateSQL(3)

print c.execute(GenerateSQL(3)).fetchall()

生成的查询如下所示:

select substr FROM

(select substr(content,0,3) AS substr, count(*) AS myCount from myTable where length(substr(content,0,3))=3 group by substr(content,0,3)

union all select substr(content,1,3) AS substr, count(*) AS myCount from myTable where length(substr(content,1,3))=3 group by substr(content,1,3)

union all select substr(content,2,3) AS substr, count(*) AS myCount from myTable where length(substr(content,2,3))=3 group by substr(content,2,3)

union all select substr(content,3,3) AS substr, count(*) AS myCount from myTable where length(substr(content,3,3))=3 group by substr(content,3,3)

union all select substr(content,4,3) AS substr, count(*) AS myCount from myTable where length(substr(content,4,3))=3 group by substr(content,4,3)

... )

GROUP BY substr HAVING sum(myCount) > 1

其产生的结果是:

[(u'app',), (u'ati',), (u'ion',), (u'nat',), (u'pin',), (u'ple',), (u'ppl',), (u'tio',)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值