'SQL join each row in a table with a one row from another table

The Problem

I have a table window with start and end timestamps. I have another table activity that has a timestamp. I would like to create a query that:

  • For each row in activity it joins with a single row from window, where the timestamp occurs between start and end, choosing the older window.

Window Table

Start End ISBN
0 10 "ABC"
5 15 "ABC"
20 30 "ABC"
25 35 "ABC"

Activity Table

Timestamp ISBN
7.5 "ABC"
27.5 "ABC"

Desired Result

Start End ISBN Timestamp
0 10 "ABC" 7.5
20 30 "ABC" 27.5

The Attempt

My attempt at solving this so far has ended with the following query:

SELECT
    *
FROM
    test.activity AS a
    JOIN test.`window` AS w ON w.isbn = (
        SELECT
            w1.isbn
        FROM
            test.window as w1
        WHERE a.`timestamp` BETWEEN w1.`start` AND w1.`end`
        ORDER BY w1.`start`
        LIMIT 1
    )

The output of this query is 8 rows.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source