Python MYSQL dynamically select fields from one table where they exist in another

Question:

I have a table task_field where I store field headers as records that exist in another table product_wca as follows:

enter image description here

Now I have a query pulling data from the product_wca table, however I would like to select fields from this table that are in the table above as per ‘name’ field.

I’m not sure if this is possible to do in MYSQL alone as I cannot join on anything but hope it’s possible with python, please see my failed attempt at this below where I tried to add a python for loop inside the mysql select statement:

Get list of fields from first table

mycursor = mydb.cursor()

mycursor.execute("SELECT name" 
                " FROM `wfi-workflow`.task_field " 
                "where " 
                " taskid = 50 " 
                " and model = 'wca'")

My failed attempt to show select fields from another table where available in table above:

newcursor = mydb.cursor()

mycursor.execute("select distinct portfolio.id," 
        "portfolio.secid," 

                 for x in mycursor:
                    for i in x:
                        "Wca.'+i+', " 

        "portfolio.code " 
        "from portfolio_identifier portfolio " 
        "left join product_wca WCA on portfolio.secid = WCA.secid " 
        "where portfolio.account_id = 319 limit 1")

Is it possible to do what I’m attempting or another work around to only select fields from one table where they exist in another?

Asked By: rob

||

Answers:

You can’t put a for loop in the middle of an expression. Use the str.join() method to create a string containing the concatenated results.

mycursor = mydb.cursor()

mycursor.execute("""SELECT name
                FROM `wfi-workflow`.task_field
                where
                  taskid = 50
                  and model = 'wca'""")
names = ",".join("wca."+row[0] for row in mycursor)

mycursor.execute("""select distinct portfolio.id,
        portfolio.secid,""" +str(names)+ """, portfolio.code
        from portfolio_identifier portfolio
        left join product_wca WCA on portfolio.secid = WCA.secid
        where portfolio.account_id = 319 limit 1""")
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.