Python MySQLdb查询搜索多个部分关键字

时间:2017-10-19 18:08:11

标签: python mysql python-2.7

我是python和sql的新手,我现在对查询问题很困惑,一些帮助将不胜感激。

我的意思是:我有一个函数可以在MySQL表上查找文本输入的巧合。

PD:我正在使用MySQLdb

在另一个文件上加载数据库连接

代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from Config.DBConfig import *
class SomeClass:
    def Search(self):
        Fruit = 'App'
        cur.execute("SELECT reference,name FROM fruits WHERE name LIKE '%%%s%%'" % (Fruit))
        row = cur.fetchall()
        print row
Test = SomeClass()
Test.Search()

它返回正确的输出:

001 , Apples are red
002 , apples
004 , Green APPLES

但现在我想在同一文本输入字段中对2个或更多关键字执行相同的操作,并且必须返回在水果名称(两个关键字)上具有这些部分关键字的水果(引用和名称),例如:

input = 'App re'
output:
001 , Apples are red
004 , Green Apples

我无法想象如何将这些输入关键字与SQL LIKE连接起来,或者我正在寻找错误的方法(几乎可以肯定)。

需要一些帮助或指导或提示plz

对所有人来说。

编辑:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from Config.DBConfig import *
class SomeClass:
    def Search(self):
        Fruit = 'App re'
        word1, word2 = Fruit.split()
        cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%') UNION SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word1, word2))
        row = cur.fetchall()
        print row

这不是我需要的(我只想要那些有两个单词的结果),但我正在接近理想的结果。

编辑2:

终于实现了我想要的东西(可能是一种糟糕的方式,但它有效):

#!/usr/bin/python
# -*- coding: utf-8 -*-
from Config.DBConfig import *
class SomeClass:
    def Search(self):
        Fruit = input_some_text
        if len(Fruit.split()) == 1:
            cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (Fruit))
            row = cur.fetchall()
            for result in row:
                print result
        if len(Fruit.split()) == 2:
            word1, word2 = Fruit.split()
            id1 = cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word1))
            row1 = cur.fetchall()
            id2 = cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word2))
            row2 = cur.fetchall()
            final = set(row1) & set(row2)
            print list(final)
        if len(Fruit.split()) == 3:
            word1, word2, word3 = supplierName.split()
            id1 = cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word1))
            row1 = cur.fetchall()
            id2 = cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word2))
            row2 = cur.fetchall()
            id3 = cur.execute("SELECT reference,name FROM fruits WHERE name LIKE ('%%%s%%')" % (word3))
            row3 = cur.fetchall()
            final = set(row1) & set(row2) & set(row3)
            result = list(final)
            print result

0 个答案:

没有答案