1

Is there a way to use DISTINCT (or another keyword) to not display duplicate results on one column? For example if I have a table with columns: id, name and countryCode

id name countryCode
1  Dan  IE
2  John US
3  John UK
4  Bob  DE

And I don't want to display duplicates where the name is the same so the result would be:

id name countryCode
1  Dan  IE
2  John US
4  Bob  DE

If I use DISTINCT here it needs to match the whole row but I only want to omit a row if the names match. Is there a way to do this? I found a similar solution here:DISTINCT for only one Column

But this does not work for mySQL. Any help would be much appreciated.

Community
  • 1
  • 1
daninoz03
  • 65
  • 2
  • 7

4 Answers4

6

For MySQL only (and related distributions, like MariaDB), you can use GROUP BY:

SELECT id, name, countryCode FROM tablename GROUP BY name

Please note that the row to be omitted is not influenced by ORDER BY or similar statements.

This is a MySQL behavior only, traditional handling of GROUP BY states that it should only be used together with aggregated values (see MySQL Handling of GROUP BY).

Capilé
  • 2,038
  • 17
  • 14
0

In MySQL you can use variables in order to simulate ROW_NUMBER window function:

SELECT id, name, countrycode
FROM (
  SELECT id, name, countrycode,
         @rn := IF (@name = name, @rn + 1,
                    IF (@name := name, 1, 1)) AS rn
  FROM mytable
  CROSS JOIN (SELECT @rn := 0, @name := '') AS vars
  ORDER BY name, countrycode) AS t
WHERE t.rn = 1

The above query, in case of a name duplicate, selects the row having the first countrycode in alphabetical order.

Demo here

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
  • Thanks Giorgos Betsos. I tried to get this method working but it didn't like some of my column joins from other tables. I'm no pro when it comes to SQL so I just went for the GROUP BY approached mentioned above and it worked. Thanks anyway – daninoz03 Feb 03 '16 at 17:34
0

Try this:

SELECT id,name, countryCode FROM table GROUP BY countryCode
JesusIniesta
  • 10,412
  • 1
  • 35
  • 28
0

Give a row number for each group.

Query

select t1.id, t1.name, t1.countryCode from 
(
    select id, name, countryCode, 
    (
        case name when @curA 
        then @curRow := @curRow + 1 
        else @curRow := 1 and @curA := name end 
    ) + 1 as rn 
    from tblNames t, 
    (select @curRow := 1, @curA := '') r 
    order by id 
)t1 
where t1.rn = 1
order by t1.id;

SQL Fiddle demo

Ullas
  • 11,450
  • 4
  • 33
  • 50
  • Thanks Ullas. I tried to get this method working but it didn't like some of my column joins from other tables. I'm no pro when it comes to SQL so I just went for the GROUP BY approached mentioned above and it worked. Thanks anyway – daninoz03 Feb 03 '16 at 17:32