Elitmiar
Elitmiar

Reputation: 36839

How to get unique values when using a UNION mysql query

I have 2 sql queries that return results, both contain a contract number, now I want to get the unique values of contract numbers

HEre's the query

(SELECT contractno, dsignoff FROM campaigns WHERE clientid = 20010490 AND contractno != '' GROUP BY contractno,dsignoff) UNION (SELECT id AS contractno,signoffdate AS dsignoff FROM contract_details WHERE clientid = 20010490) 

So for example, if the first query before the union returns two results with contract no 10, and the sql query after the union also returns 10, then we have 3 rows in total, however because contractno of all three rows is 10, I need to have only one row returned, Is this possible?

Upvotes: 2

Views: 2602

Answers (1)

Julien Hoarau
Julien Hoarau

Reputation: 49970

You could put your current request in a temporary table, and execute a select on this table :

SELECT
  *
FROM
  (
   /* Your request goes here */
    SELECT 
      contractno, 
      dsignoff 
    FROM 
      campaigns 
    WHERE 
      clientid = 20010490 AND contractno != '' 
    GROUP BY 
      contractno,dsignoff
    UNION
    SELECT 
      id AS contractno,
      signoffdate AS dsignoff
    FROM 
      contract_details 
    WHERE clientid = 20010490) 
  ) AS tmp
GROUP BY
  tmp.contractno

(But are you sure you can't do what you want with joins?)

Upvotes: 4

Related Questions