Question

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.

Était-ce utile?

La solution

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

Autres conseils

IS this what you are looking at ?

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

DEMO

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top