JD Isaacks
JD Isaacks

Reputation: 57994

MySQL: Select Distinct from 2 different tables?

I have 2 different tables that each have a column called product_type. How can I get the DISTINCT values of product_type across both tables? Just to clarify, if both tables have a product_type of "diamond" I only want it returned once. Basically as if both tables where combined and I selected distinct product_type from it.

Thanks!!

Upvotes: 12

Views: 38319

Answers (3)

albertein
albertein

Reputation: 27130

Use a distinct with a subquery which contains a union

select distinct product_type from (
    select product_type from table 1
    union 
    select product_type from table 2
) t

Upvotes: 28

Guffa
Guffa

Reputation: 700552

Use distinct and union:

select distinct product_type from table1
union
select distinct product_type from table2

The union will remove duplicates when combining the results.

Upvotes: 9

tekBlues
tekBlues

Reputation: 5793

Note that the UNION clause returns unique values of the field, when you want it to return ALL the values you must use UNION ALL...

select product_type from table_a
union
product_type from table_b

Upvotes: 1

Related Questions