[英]SQL Join and Check If In List
TABLE1
TEACHER DATE1 DATE2
1 2018-04-28 2019-05-30
1 2019-09-03 2019-09-06
1 2019-10-13 2019-12-21
2 2018-01-10 2018-12-30
2 2019-09-18 2019-11-03
3 2018-01-04 2019-07-27
4 2018-05-08 2019-01-19
4 2019-11-09 2019-11-20
TABLE2
STUDENT TEACHER DATE
1 2 2019-08-09
1 2 2018-12-16
1 4 2018-11-01
1 2 2018-10-31
1 4 2019-09-05
2 3 2019-08-13
2 3 2019-10-19
2 4 2018-09-16
2 1 2018-06-12
2 3 2019-03-02
2 4 2018-12-19
2 4 2019-04-24
2 4 2018-09-16
I have TABLE1 and TABLE2.我有 TABLE1 和 TABLE2。 I wish to join TABLE1 and TABLE2 to make table WANT我希望加入 TABLE1 和 TABLE2 来创建表 WANT
WANT
STUDENT TEACHER DATE
1 2 2018-12-16
1 2 2018-10-31
1 4 2018-11-01
2 1 2018-06-12
2 3 2019-03-02
2 4 2018-12-19
2 4 2019-04-24
Basically I wish to include in WANT only rows where the DATE is between DATE1 and DATE2 for every TEACHER in TABLE1.基本上,对于 TABLE1 中的每个教师,我希望只在 WANT 中包含日期介于 DATE1 和 DATE2 之间的行。
For example in TABLE 2 there is this row例如在表 2 中有这一行
1 2 2019-08-09
that does not come into table WANT because the DATE value 2019-08-09 is not in between the VALID DATES for TEACHER=2 shown in TABLE1.这不会进入表 WANT,因为日期值 2019-08-09 不在 TABLE1 中显示的 TEACHER=2 的有效日期之间。
I try this without success我尝试这个没有成功
SELECT * FROM TABLE2
WHERE
TEACHER IN (SELECT TEACHER FROM TABLE1)
AND DATE >= (SELECT DATE1 FROM TABLE1)
AND DATE <= (SELECT DATE2 FROM TABLE1)
In your case INNER JOIN
would work just fine在你的情况下INNER JOIN
会工作得很好
SELECT t2.STUDENT, t2.TEACHER, t2.DATE FROM TABLE2 t2
INNER JOIN TABLE1 t1 ON t2.TEACHER = t1.TEACHER
WHERE
AND t2.DATE >= t1.DATE1
AND t2.DATE <= t1.DATE2
But be aware that there might be duplicates for Students if there are overlapping Teacher records in Table1 by dates, for example if there are 2 records for the same Teacher with same dates (or overlapping dates, like first one is 2022-01-01
2023-01-01
and second one is 2022-06-06
2023-06-06
, and student date is 2022-07-01
)但请注意,如果表 1 中的教师记录按日期重叠,则学生可能会重复,例如,如果同一位教师有 2 条具有相同日期(或重叠日期,例如第一个是2022-01-01
2023-01-01
)的记录2023-01-01
和第二个是2022-06-06
2023-06-06
,学生日期是2022-07-01
)
Since you are only after qualifying rows from table2, the optimal way to write this would be to use a semi-join with exists :由于您仅在对 table2 中的行进行限定之后,因此编写此代码的最佳方法是使用带有exists的半连接:
select *
from t2
where exists (
select * from t1
where t1.teacher = t2.teacher
and t2.date >= t1.date1
and t2.date <= t1.date2
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.