简体   繁体   中英

Filter rows from table 1 with table 2 info

I have 2 tables. One table listing results of a run and a 2nd table with timestamps.

table1 (not sure how to add another column to the table but table 1 has an end time also that will need to be filtered out):

Tenant start
x 2022-05-01 23:00:00
x 2022-05-02 02:00:00
x 2022-05-02 06:00:00

table 2:

start end
2022-05-01 23:00:00 2022-05-02 03:00:00

The goal is to filter out/ exlude rows from table 1 that fall in between start/end time from table 2.

The results should be :

Tenant start
x 2022-05-02 06:00:00

I tried doing below:

select *
from table 1
where start not in (select start from table 2)

But does not seem to work correctly.

Using exists logic we can try:

SELECT t1.*
FROM table1 t1
WHERE NOT EXISTS (
    SELECT 1
    FROM table2 t2
    WHERE t1.start BETWEEN t2.start AND t2.end
);

For your updated requirement, we could select an exists boolean expression:

SELECT t1.*, NOT EXISTS (
    SELECT 1
    FROM table2 t2
    WHERE t1.start BETWEEN t2.start AND t2.end
) AS mw
FROM table1 t1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM