如何从引用的表中具有匹配ID的表中选择表的列项目

时间:2018-12-28 17:48:58

标签: inner-join peewee flask-peewee

我有两个表:

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 |
+----+--------+----------+---------------+-----+--------+

第二个表是相对的;

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

我想使用peewee方法获取患者ID与亲戚ID匹配的亲戚列表

我试图创建这样的联接:

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

但给出错误提示:

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

我知道了:

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

但是它返回所有的relativeNames而不是具有匹配ID的名字。

1 个答案:

答案 0 :(得分:0)

想通了:

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