Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract a query result from another query result in MYSQL

1st query

   (SELECT a.cat_id, 
          a.cat_name, 
          a.cat_description, 
          b.subcat_name, 
          b.subcat_description 
     FROM trade_categories a 
LEFT JOIN trade_subcategories b ON a.cat_id = b.cat_id 
    WHERE a.cat_name LIKE '%catty%' 
       OR a.cat_description LIKE '%catty%') 
UNION 
  (SELECT c.cat_id, 
          d.cat_name, 
          d.cat_description, 
          c.subcat_name, 
          c.subcat_description 
     FROM trade_subcategories c 
LEFT JOIN trade_categories d ON c.cat_id = d.cat_id 
    WHERE c.subcat_name LIKE '%catty%' 
       OR c.subcat_description LIKE '%catty%') 

2nd query :

SELECT x.cat_id, 
       x.cat_name, 
       x.cat_description, 
       y.subcat_name, 
       y.subcat_description 
 FROM  trade_categories x 
  JOIN trade_subcategories y ON x.cat_id = y.cat_id 
 WHERE (   x.cat_name LIKE '%catty%' 
        OR x.cat_description LIKE '%catty%' ) 
   AND (   y.subcat_name NOT LIKE '%catty%' 
        OR y.subcat_description NOT LIKE '%catty%' )

I want to subtract the 2nd query result from 1st query result.

like image 335
merlin Avatar asked Jun 17 '11 00:06

merlin


People also ask

How do I subtract one query from another in MySQL?

You could simply do... SELECT Total1, Total2, Total1 - Total2 FROM (SELECT SUM(id) Total1 FROM TableA) AS a INNER JOIN (SELECT SUM(id) Total2 FROM TableB) AS b; In your case, the two subqueries, a and b , would be replaced with the two queries you currently have for calculating sums.

How do you subtract one value from another in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

Does MINUS work in MySQL?

MySQL Does not supports MINUS or EXCEPT ,You can use NOT EXISTS , NULL or NOT IN .


2 Answers

I think you can either do a NOT IN or a LEFT JOIN. I'd prefer a LEFT JOIN.

So for example,

SELECT `QUERY_ONE`.*
FROM `QUERY_ONE`
LEFT JOIN `QUERY_TWO` USING (`cat_id`)
WHERE QUERY_TWO.cat_id IS NULL;

where QUERY_ONE and QUERY_TWO are aliases for your two queries

like image 27
Abhay Avatar answered Nov 14 '22 23:11

Abhay


http://www.bitbybit.dk/carsten/blog/?p=71

or example:

SELECT Name FROM employee1  WHERE name NOT IN (SELECT name FROM employee2);
like image 113
Bart Avatar answered Nov 14 '22 21:11

Bart