Search code examples
inner-joinpeeweeflask-peewee

How to select column items of a table from a table with matching id in table referenced


I have two tables:

select * from patient WHERE name = 'Dharam';
+----+--------+----------+---------------+-----+--------+
| id | name   | townCity | contactnumber | age | gender |
+----+--------+----------+---------------+-----+--------+
|  5 | Dharam | sdfgsgfs | 252232        |   6 | Male   |
|  6 | Dharam | sdfgsgfs | 252232        |   6 | Male   |
| 12 | Dharam | sadasda  | 213214124     |   2 | Female |
+----+--------+----------+---------------+-----+--------+

and second table is Relative;

+----+------------+----------+--------------+
| id | patient_id | relation | relativeName |
+----+------------+----------+--------------+
|  5 |          5 | Son      | Gyan         |
+----+------------+----------+--------------+
|  6 |          6 | Son      | Gyan         |
+----+------------+----------+--------------+
| 12 |         12 | Wife     | Suvidha      |
+----+------------+----------+--------------+

I want to get the list of relative names whose patient ids are matching id of relatives using the peewee approach

I tried to create a join like this:

select id, name from patient INNER JOIN  relative ON 
(patient.id == relative.id) WHERE patient.name = 'Dharam';

but gives error saying:

 MariaDB server version for the right syntax to use
 near '= relative.id) WHERE patient.name = 'Dharam'' at line 1

I figured out this:

 query = (Relative.select(Relative.relativeName, Patient.id).join(Patient).where(Patient.id == Relative.id))
>>> 
>>> for item in query: print item.relativeName

but it returns all the relativeNames rather than the ones with matching ids.


Solution

  • Figured out :

    >>> query = (Relative.select(Relative.relativeName).join(Patient).where(Patient.name == 'Dharam'))
    >>> for item in query: print item.relativeName