SQL / Postgres连接where子句

时间:2019-12-19 18:14:00

标签: sql postgresql join where-clause

我有2张桌子观察和研究。 研究包含研究的名称(研究),研究中每个对象的ID以及开始日期和结束日期

观察结果包含ID,日期(观察日期)和观察结果(列名“评论”)

我想从研究中获取与研究名称匹配的所有ID(从研究中选择研究ID为“ ST009”的ID) 然后,我想从与2个日期(日期可以是任意2个日期,不限于start_date和end_date)之间的研究ID匹配的观察值中获取所有观察值

研究表:

study   id   start_date   end_date
ST0009  A    2019-01-01   2019-02-15
ST0009  B    2019-01-01   2019-02-15
ST0009  C    2019-01-01   2019-02-15
ST0010  D    2019-01-10   2019-02-20
ST0010  D    2019-01-10   2019-02-10

观察表

date       id  comments
2019-01-02 A   Cracks on edges
2019-01-02 B   Soft center
2019-01-10 A   Cracks moving to the center
2019-01-11 D   Curled edges 
2019-01-12 A   Edges separating from body
2019-01-15 D   Curled edges cracking
2019-01-25 B   Center becoming solid

结果:

ID  observations.date observations.comment
A   2019-01-02       Cracks on edges
A   2019-01-10       Cracks moving to the center
A   2019-01-12       Edges separating from body
B   2019-01-02       Soft center
B   2019-01-25       Center becoming solid
C

希望这是有道理的

1 个答案:

答案 0 :(得分:0)

只需联接表并在WHERE子句中应用过滤器即可。

SELECT s.*
       FROM observation o
            INNER JOIN study s
                       ON s.id = o.id
       WHERE s.study = 'ST009'
             AND o.date >= '$from'
             AND o.date < '$to';

$from$to是您的任意两个约会。