title: Mysql: Subtraction between rows and sum with other table
body: <p>I have two tables, both with a Time column as timestamp type which is filled by default when the row is created: Table1 is updated approximately every 10 seconds:</p>
  <pre><code>         Time       | Val_1a | Val_2a | Val_3a 
  2021-11-06 13:59:53 |  15    |  10    |  35
  2021-11-06 14:00:02 |  12    |  15    |  34
  .................         
  2021-11-06 14:05:25 |  11    |  13    |  35
  2021-11-06 14:05:35 |  11    |  17    |  36
  </code></pre>
  <p>Table2 is updated every hour after mathematical operations on table1:</p>
  <pre><code>         Time       | Var_1b | Var_2b | Var_3b            
  2021-11-06 11:00:00 |  2     |  15    |  30
  2021-11-06 12:00:00 |  8     |  12    |  32
  2021-11-06 13:00:00 |  12    |  11    |  35
  </code></pre>
  <p>What I would like to get but I'm not able to do in any way, is:</p>
  <ol>
  <li>Check that the last table1.Val_2a value is greater than the first table1.Val_2a value written at the beginning of the current hour (with the tables above, check if 17 &gt; 15). If this condition is not met, the entire query must return 0 otherwise:</li>
  </ol>
  <p>2a) If the last row in table2 refers to the previous day, then the query result is simply the difference of the two table1.Val_2a values (17 - 15 = 2)</p>
  <p>2b) Otherwise their difference is calculated as at point 2a (17-15 = 2) and it is added to the table2.Var_1b value (2 + 12 = 14)</p>
  <p>I hope I was able to explain it in a clearly way, and that it all is possible with a single query. Thanks everyone for the support</p>