Doing it in Python

As we have seen in previous chapters, processing a SELECT query in Python is as simple as execute() and fetchall(). However, Python also allows us to build statements dynamically, and this applies to joins, unions, and subqueries as well.

Subqueries

If we want column from table1, but the column reference for the subquery is colref, from both table1 and table2, we can write the following:

#!/usr/bin/env python import MySQLdb mydb = MySQLdb.connect('localhost', 'skipper', 'secret', 'sakila') cursor = mydb.cursor() table1 = 'film' table2 = 'film_actor' column = 'film_id, title' colref = 'film_id' statement = "SELECT %s FROM %s WHERE %s IN (SELECT %s FROM %s)" %(column, table1, colref, colref, table2) cursor.execute(statement) results ...

Get MySQL for Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.