Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL JOIN based on highest date and non-unique columns
    primarykey
    data
    text
    <p>I need some help with a MySQL query I'm working on. I have data as follows.</p> <p>Table 1</p> <pre><code>id date1 text number ---|------------|--------|------- 1 | 2012-12-12 | hi | 399 2 | 2011-11-11 | so | 399 5 | 2010-10-10 | what | 555 3 | 2009-09-09 | bye | 300 4 | 2008-08-08 | you | 300 </code></pre> <p>Table 2</p> <pre><code>id number date2 ref ---|--------|------------|---- 1 | 399 | 2012-06-06 | 40 2 | 399 | 2011-06-06 | 50 5 | 555 | 2011-03-03 | 60 </code></pre> <p>For each row in Table 1, I want to get zero or one ref values from Table 2. There should be a row in the result for each row in Table 1. The number column isn't unique to either table, so the join must be made using the date1 &amp; date2 columns, where date2 is the highest value for the number without exceeding date1 for that number.</p> <p>The desired result from the above example would be like so.</p> <pre><code> date1 text number ref ------------|--------|--------|----- 2012-12-12 | hi | 399 | 40 2011-11-11 | so | 399 | 50 2010-10-10 | what | 555 | null 2009-09-09 | bye | 300 | null 2008-08-08 | you | 300 | null </code></pre> <p>You can see in the result's first row, ref is 40 was chosen because in table2 the record with ref=40 had a date2 that that was less than date1, and the highest date that met that condition. In the result's second row, ref is 50 was chosen because in table2 the record with ref=50 had a date2 that that was less than date1, and the highest date that met that condition. The rest of the results have null refs because date1 is always less or a corresponding number doesn't exist in table2.</p> <p>I've got to a certain point but I'm stuck. The query I have so far is like this.</p> <pre><code>SELECT date1, text, number, ref FROM table1 LEFT JOIN ( SELECT * FROM ( SELECT * FROM table2 WHERE date2 &lt;= '2012-12-12' ORDER BY date2 DESC ) tmp GROUP BY msisdn ) tmp ON table1.number = table2.number; </code></pre> <p>The problem is that the hard coded date won't do, it should be based on date1, but I can't use date1 because it's in the outer query. Is there a way I can make this work?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload