title: MySQL Interval Variables And Subquery Notation
body: <p>I inherited this MySQL query as a bit of legacy code:</p>
  
  <pre><code>       SELECT
          HardwareAddress, CONV(SUBSTRING(EventValue,3,2), 16, 10) AS 'Algorithm'
          FROM ( SELECT @prev := '') init
          JOIN
              ( SELECT HardwareAddress != @prev AS first,
                  @prev := HardwareAddress,
                  HardwareAddress, EventValue, ID
                  FROM Events   
                      WHERE Time &gt; {unixtime}
                      AND EventType = 104
                      AND HardwareAddress IN ({disps})
                      ORDER BY
                          HardwareAddress,
                          ID DESC
              ) x
         WHERE first;
  </code></pre>
  
  <p><code>{unixtime}</code> and <code>{disps}</code> are variables that are filled with the Python String.format() method.</p>
  
  <p>I'm having a hard time creating new functionality out of this query because no one else understands how it works, and I haven't been able to find adequate documentation. All I know is that the query pulls a list of values called 'algorithm' from a long hex string sent by IoT devices.</p>
  
  <p>I roughly understand how the subselect and the interval variables are working, but there is a lot I don't understand. How does the <code>FROM (SELECT @prev := '') init</code> line work? The last two lines of the query also confound me. Why is the subquery aliased to <code>x</code> when nothing is referencing it, and what on earth does the <code>WHERE first</code> mean?</p>
  
  <p>If someone is able to walk me through what this bit of code is doing, I'd be very grateful.</p>