1

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?

0

2 Answers 2

1

Simply (append to a query):

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply, please have a look to my code again, I just modified my question.
0

Like this ?

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

This will works perfectly but if self.X and self.Y different from integer 0 value because integer 0 equal to boolean False. in this use this code

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

1 Comment

Thanks for your reply, please have a look to my code again, I just modified my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.