0

Good day all.

I'm facing a little problem with a mySql query. let's assume we have a table with a coulmn in which the values are pairs, but unified in the same field, so something like this:

id  |  serviceName
----+-------------
1   |  foo - bar
2   |  foo - doo
3   |  foo - tep
4   |  bee - bar
5   |  bee - blo

I would like to select distinct the first part of serviceName, in this case foo, bee.

the desired output should be:

foo
bee

in the resultset.

what I've thought right now is something about making a SELECT DISTINCT a FROM REPLACE ( (SELECT serviceName as a FROM tableName), ' - ***', '')

but i'm not really sure if it is possible, and how to make it. I only would like to select the first part of the field, and I would like to take only distinct vlaues of it... it is possible? I need a right direction pointing,, I can make researches by my self.

thanks in advance.

Matteo Bononi 'peorthyr'
  • 2,170
  • 8
  • 46
  • 95

2 Answers2

1

Assuming that you always want to split on a dash -, this should work for you.

SELECT DISTINCT LEFT(serviceName, LOCATE('-', serviceName) - 2) FROM tableName;

SQLFiddle

Patrick Q
  • 6,373
  • 2
  • 25
  • 34
  • this is also a really good way, is the distinct better than the other solution? – Matteo Bononi 'peorthyr' Apr 18 '14 at 15:14
  • 1
    @MatteoBononi'peorthyr' Performance-wise, there isn't much/any noticeable difference. Although I believe that if you get very specific, `DISTINCT` may be _slightly_ faster. That being said, if you want to do something like get the count of how many entries match each first section, then you'll want to use `GROUP BY`. – Patrick Q Apr 18 '14 at 15:17
1

IS this what you are looking at ?

select substring_index(serviceName,'-',1) as `first_part` 
from test
group by `first_part`

DEMO

Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63