Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's the order of how things are executed in a database engine.</p> <p>Note that this is a semantic view of how things are executed, the database might do things in a different order, but it has to produce results as though it was done this way.</p> <ol> <li>First the FROM-part is evaluated, where do I get data from</li> <li>Then the WHERE-part is evaluated, which rows are we interested in</li> <li>Then the GROUP BY-part is evaluated, how do we combine the resulting rows</li> <li>Then the HAVING-part is evaluated, which groups are we interested in</li> <li>Then the ORDER BY-part is evaluated, which order do we want those rows/groups</li> <li>Finally, the SELECT-part is evaluated, which columns are we interested in</li> </ol> <p>Some database engines allows you to circumvent this though, by saing "GROUP BY 2" to group by the 2nd column in the SELECT-part, but if you stick to the above order, you should know by now that the reason that your code doesn't work is that there are no columns with the names total or total2 (yet).</p> <p>In other words, you need to either repeat the two expressions, or find another way of doing it.</p> <p>What you can do is to use a sub-query (providing you're on a MySQL version that supports this):</p> <pre><code>SELECT total, total2, total+total2 as grandtotal FROM ( SELECT sum(EXPR) as total, sum(EXPR) as total2 FROM tablename ) x </code></pre> <p>Striking out the rest as per the comment.</p> <p><strike>I don't know much about MySQL though so you might have to alias the sub-query:</p> <pre><code>... FROM tablename ) AS x ^-+^ | +-- add this </code></pre> <p>Some database engines also disallow using the keyword AS when aliasing subqueries, so if the above doesn't work, try this:</p> <pre><code>... FROM tablename ) x ^ | +-- add this </code></pre> <p></strike></p>
 

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