I am using python mysql to grab the data from the database. But I don't know how to merge three very similar queries in one single query.This is my code:
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)
As you see the only difference between three queries is in one line. How can I make my code more solid?