Retrieving Specific Columns from a JOIN Query
In the previous exercise, we saw that we can use a JOIN
to fetch the related rows from two tables. However, if we look at the results, we will see that it returned all the columns, thus combining both tables. This is not very concise. What about if we only want to see the emails and the related comments, and not all the data?
There is some nice shorthand code that lets us do this:
import sqlite3 with sqlite3.connect("../lesson.db") as conn: Â Â Â Â cursor = conn.cursor() Â Â Â Â cursor.execute("PRAGMA foreign_keys = 1") Â Â Â Â sql = """ Â Â Â Â SELECT comments.* FROM comments \ Â Â Â Â JOIN user ON comments.user_id = user.email \ Â Â Â Â WHERE user.email='bob@example.com' \ Â Â Â Â """ Â Â Â Â rows = cursor.execute(sql) Â Â Â Â for...