Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>MySQL is flexible in <code>SELECT</code> list subqueries, so you can do something like the following, without even needing a <code>FROM</code> clause on the main query.</p> <pre><code>SELECT (SELECT SUM(costres) - SUM(costadmin) FROM call_history, client WHERE MONTH(start) = 3 AND YEAR(start) = 2012 AND call_history.client_reseller_id = client.id AND client.charging_identifier &lt;&gt; 100000 AND client.charging_identifier &lt;&gt; 999999 ) + ( SELECT SUM(costcl) - SUM(costadmin) FROM call_history, client WHERE MONTH(start) = 3 AND YEAR(start) = 2012 AND call_history.client_reseller_id = client.id AND client.charging_identifier = 100000 AND client.charging_identifier &lt;&gt; 999999 ) AS yourSum; </code></pre> <p>I can't remember if MySQL permits <code>UNION</code> inside subqueries. If it does, it is a little nicer to use <code>SUM()</code> them across a <code>UNION</code>:</p> <pre><code>SELECT SUM(total) as grand_total FROM ( SELECT SUM(costres) - SUM(costadmin) AS total FROM call_history, client WHERE MONTH(start) = 3 AND YEAR(start) = 2012 AND call_history.client_reseller_id = client.id AND client.charging_identifier &lt;&gt; 100000 AND client.charging_identifier &lt;&gt; 999999 UNION ALL SELECT SUM(costcl) - SUM(costadmin) AS total FROM call_history, client WHERE MONTH(start) = 3 AND YEAR(start) = 2012 AND call_history.client_reseller_id = client.id AND client.charging_identifier = 100000 AND client.charging_identifier &lt;&gt; 999999 ) unionsub </code></pre> <h3>Update:</h3> <p>A quick test tells me that you can use <code>UNION ALL</code> in a subquery, at least in MySQL 5.6.</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.
    1. VO
      singulars
      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