我使用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)
关于python - MySQL中的Python动态查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57542861/