import pymysql # [1] Making connection to the MySQL server cnx = pymysql.connect(user='demo', password='abcdef', host='localhost', database='toyu') # Create a cursor using the connection. cursor = cnx.cursor() # [2] Prepare a SQL query for the problem query = ''' SELECT CONCAT (s.fname, ' ', s.lname) AS student, d.deptName, CONCAT(f.fname, ' ', f.lname) as advisor FROM student AS s LEFT JOIN department AS d ON (s.major = d.deptCode) LEFT JOIN faculty AS f ON (s.advisor = f.facId); ''' # Execute the query cursor.execute(query) # [3] Use the result in the query for (student, major, advisor) in cursor: print("{}: major={}; advisor={}".format(student, major, advisor)) # [4] Housekeeping cursor.close() cnx.close()