Python mysql 中的动态查询

Python dynamic query in mysql

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

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)

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

像这样?

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 "")

简单地(附加到查询):

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)