heltonbiker
heltonbiker

Reputation: 27615

Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3

I have a small database which is legacy from an almost defunct project. This database has a "Patients" table with individual personal data and an unique "Id" field, and an "Exams" table with some fields for each exam, one of these fields being "Patient_Id".

What I want is, for a given patient (row from "Pacientes" table) the exams (rows) from "Exames" table whose "Patient_Id" matches that of the given patient.

I am very beginner with SQL, so if the question is very naive, I apologize.

My working code is the following, but I am using a for loop while I would much rather have a SQL query (which is the very point of using databases, I think...):

#!/usr/bin/env python
# coding: utf-8

import os, sqlite3

conn = sqlite3.connect('BDdata.db3')
conn.row_factory = sqlite3.Row
c = conn.cursor()

c.execute('SELECT * FROM Exames')
exams = c.fetchall()

c.execute('SELECT * FROM Pacientes')
for row in c:
    Nome = row['nome']
    ID = row['Id']
    for exam in exams:          # I would like to replace this loop
        if exam['Id_Paciente'] == ID:       # with a SQL query meaning
            print exam['File']

============================

An answer to a similar question seems to be what I want, but I have no idea how to do this in Python with sqlite3 module, much less what in this expression is essential and what is incidental, or what is the syntax structure:

Selecting rows from a table by One a field from other table

SELECT i.prof_image 
FROM profile_images i 
WHERE cat_id = (select max(cat_id) from images_cat)

Upvotes: 0

Views: 589

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208715

I think the following should do what you want:

...
c = conn.cursor()

c.execute('SELECT * FROM Pacientes')
for row in c.fetchall():
    Nome = row['nome']
    ID = row['Id']
    c.execute('SELECT File FROM Exames WHERE Id_Paciente=?', [ID])
    for exam in c:
        print exam['File']

Upvotes: 1

Related Questions