Search code examples
pythonpymysql

pymysql-Combining the results of two different queried into


I have done something like this:

sql_query1=...
sql_query2=...

cur.execute(sql_query1,(actorId1,actorId2))
results1=cur.fetchall()

cur.execute(sql_query2,(actorId1,actorId2)) 
results2=cur.fetchall()

nested_tuple_list1=[]
for result in results1:
    nested_tuple_list1.append(result) 

return(nested_tuple_list1) 

nested_tuple_list2=[]
for result in results2:
    nested_tuple_list2.append(result) 

return(nested_tuple_list2) 

and I want to get the common results of the two queries.Any idea on what could I do?

An example of what I need:

jim | tim | a      jim | dan | b
dan | mo  | b      dan | mo  | b
jim | dan | c       

I want to get:

dan | mo | b

Solution

  • It's a bit unclear what you're trying to achieve, but if you're working with lists the easiest way is:

    intersection=[value for value in nested_tuple_list1 if value in nested_tuple_list2]

    The above also holds for tuples in a list, assuming that you are matching the tuple as a whole, and not the elements in it. So for example

    a=[(1, 2), (18, 3), (9, 8), (11, 83)]
    b=[(4, 3), (8, 47), (42, 77), (1, 2), (3, 18)]
    
    intersection=[value for value in a if value in b]
    

    The result I get is:

    [(1, 2)]
    

    If you want to compare the tuples in the list element-wise, it's a bit more complicated but also doable.