title: Using IF output as a variable in MySQL
body: <p>I have a table <code>alpha</code> has 3 column which <code>id (INT)</code> and <code>time1, time2 (DATETIME)</code></p>
  
  <p>Now I want to count how many rows in every day from <code>2017-04-18</code> to <code>2017-05-24</code> and I tried this query but failed</p>
  
  <pre><code>SELECT IF(time1 &lt; time2, time2, time1) AS d, COUNT(DATE(d)) FROM alpha 
  WHERE time1 IS NOT NULL AND time2 IS NOT NULL
  AND DATE(d) BETWEEN DATE('2017-04-18') AND DATE('2017-05-24')
  </code></pre>
  
  <p>Data</p>
  
  <pre><code>ID  TIME1                  TIME2
  -----------------------------------------------
  1, '2017-04-19 04:08:03', '2017-04-19 04:08:03'
  2, '2017-04-19 04:08:03', '2017-05-19 04:08:03'
  3, '2017-06-19 04:08:03', '2017-04-19 04:08:03'
  4, '2017-06-19 04:08:03', '2017-06-20 04:08:03'
  5, '2017-05-19 04:08:03', '2017-05-01 04:08:03'
  </code></pre>
  
  <p>Expected result</p>
  
  <pre><code>DAY         COUNT
  ---------------------
  2017-04-19  1
  2017-05-19  2
  </code></pre>