What's the best way to combine 2 tables in MYSQL and remove duplicates?

Go To StackoverFlow.com

1

I have 2 tables:

matches TABLE
   FIELDS: record, date, competition

outrights TABLE
   FIELDS: record, competition

What I would like, is to select rows grouped by the different types of competition. Below are the statements that work fine when I treat each table seperately.

Firstly, from 'matches' and only if the date hasn't already past:

SELECT competition, date FROM matches WHERE date >= '$currentTime' GROUP BY competition

Followed by rows from 'outrights':

SELECT competition FROM outrights GROUP BY competition

This is all pretty straight forward, except the same competition values will often (but not always) appear in both tables. I have looked at many different methods (including LEFT and RIGHT JOINS), but haven't found a simple solution. Basically I want the different competition types that appear in both tables, without duplication. Is this possible?

2012-04-05 00:11
by user1267980


4

Is this what you are looking for. A little confused by the question but it appears that you want a DISTINCT listing of the competition column from both tables

SELECT DISTINCT competition 
FROM
(
    SELECT competition  FROM matches
    UNION
    SELECT competition from outrights
) AS t

If you need the distinct competitions that appear only in both tables and not just one or both you could use

SELECT DISTINCT competition 
FROM
(
    SELECT competition  FROM matches INNER JOIN 
        outrights ON matches.competition = outrights.competition
) AS t
2012-04-05 00:21
by Dan P
You've done it Dan, even though my answer confused you! Thanks for saving me hours of frustration - user1267980 2012-04-05 00:33
Ads