pm1359
pm1359

Reputation: 632

Mysql query when a condition valids then extract string

I have several fields containing the following contents. I want my query meets all the following fields but with the following conditions:

I have tried something like:

select  left(provider,locate('.',provider)-1) from test group by provider;

But this returns as below and this is not what I want. I don't know how to change it to have the desired results.

 vipin3601 vipinstm vipout382 vipoutils vipoutiot vipoutxxp vipoutqlm vipoutspm

Thank you for any helps.

Upvotes: 1

Views: 47

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

You are basically going to need to build out a complex case statement here. That might look like:

SELECT
  CASE
    /* vipin case */
    WHEN provider LIKE 'vipin%.%'
        /* grab substring up to first '.'
         * then get substring of that starting at 6th position
         * to accomodate for 5 letters in 'vipin'
         */
        THEN SUBSTRING(SUBSTRING_INDEX(provider, '.', 1), 6)
    /* vipout case */
    WHEN provider LIKE 'vipout%.%'
        /* grab substring up to first '.'
         * then get substring of that starting at 6th position
         * to accomodate for 6 letters in 'vipout'
         */
        THEN SUBSTRING(SUBSTRING_INDEX(provider, '.', 1), 7)
    /* all other cases */
    ELSE provider
  END AS result
FROM test

Note that I did not include your GROUP BY clause as it does not seem to do anything here, since there are no aggregation functions being used.

Upvotes: 2

Giorgos Betsos
Giorgos Betsos

Reputation: 72175

Try this:

SELECT CASE 
          WHEN provider LIKE 'vipin%.%' 
             THEN SUBSTRING_INDEX(SUBSTRING_INDEX(provider, '.', 1), 'vipin', -1) 
          WHEN provider LIKE 'vipout%.%' 
             THEN SUBSTRING_INDEX(SUBSTRING_INDEX(provider, '.', 1), 'vipout', -1) 
       END
FROM test
WhERE provider LIKE 'vipin%.%' OR provider LIKE 'vipout%.%'

Upvotes: 0

Related Questions