繁体   English   中英

mysql中的Python动态查询

[英]Python dynamic query in mysql

我正在使用 python mysql 从数据库中获取数据。 但我不知道如何在一个查询中合并三个非常相似的查询。这是我的代码:

if self.X and not self.Y:
        query = """
            SELECT tb1.email
            FROM table1 as tb1
            join table2 as tb2 ON tb2.id= tb1.p_id
            WHERE tb2.id={}
            """.format(self.X)

elif self.X and self.Y:
      query = """
            SELECT tb1.email
            FROM table1 as tb1
            join table2 as tb2 ON tb2.id= tb1.p_id
            WHERE tb2.id={}
            AND tb1.id ={}
            """.format(self.X, self.Y)
else:
    query = """
        SELECT tb1.email
        FROM table1 as tb1
        join table2 as tb2 ON tb2.id= tb1.p_id
        WHERE tb1.id={}
        """.format( self.Y)

如您所见,三个查询之间的唯一区别是在一行中。 我怎样才能使我的代码更可靠?

简单地(附加到查询):

query = """
    SELECT tb1.email
    FROM table1 as tb1
    join table2 as tb2 ON tb2.id= tb1.p_id
    WHERE {}.id = {}
    """

if self.X:
    query = query.format('tb2', self.X)
    if self.Y: query += f' AND tb1.id = {self.Y}'
elif self.Y:
    query = query.format('tb1', self.Y)

像这样 ?

if(self.X):
    query = """
        SELECT tb1.email
        FROM table1 as tb1
        join table2 as tb2 ON tb2.id= tb1.p_id
        WHERE tb2.id=%s
        %s"""%(self.X,"AND tb1 = %s"%(self.Y) if self.Y else "")

这将完美运行,但如果 self.X 和 self.Y 与整数 0 值不同,因为整数 0 等于布尔值 False。 在此使用此代码

if(type(self.X)==int):
        query = """
        SELECT tb1.email
        FROM table1 as tb1
        join table2 as tb2 ON tb2.id= tb1.p_id
        WHERE tb2.id=%s
        %s"""%(self.X,"AND tb1 = %s"%(self.Y) if type(self.Y)==int else "")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM