Join tables on nearest date in the past, in MySQL

前端 未结 3 746
别那么骄傲
别那么骄傲 2020-12-19 15:56

I have a sqlite query that I\'m trying to write. I have two tables:

TableA (sales): id sales date

TableB (goals): id goal date

I\'m selecting from Ta

相关标签:
3条回答
  • 2020-12-19 16:03
    SELECT a.id, a.sales, a.date, (SELECT TOP 1 Goal 
                                   FROM TableB b WHERE b.date < a.date
                                   ORDER BY b.date DESC) As Goal
    FROM TableA a
    

    Going off the nearest date in the past.

    0 讨论(0)
  • 2020-12-19 16:19

    "Exactly equal date" would be a join on the date field. (As in Ash's answer)

    "Nearest date" should probably read something like "nearest date in the future" or "nearest date in the past" (or maybe not). In this case you can use a subquery with a WHERE statement comparing the dates (< or >)

    If "nearest date" is both in past and present, I'd probably code it by writing a stored procedure which creates a helper table containing the most relevant 'near date' (From B) for every date in table A. This way I'd have more control over the behaviour of the procedure and it'd be easier to change in the future.

    Optimization for performance can always happen later.

    0 讨论(0)
  • 2020-12-19 16:23

    Just get the cartesian product and then filter out uninteresting rows. Basically:

    select a.*, b.*
    from a, b
    where
    not exists (
      select null
      from b b2
      where abs(b2.date - a.date) < abs(b.date - a.date)
    )
    

    I don't know if SQLite supports that, tough.

    0 讨论(0)
提交回复
热议问题