MySQL Case in Select Statement with LIKE operator

后端 未结 4 1434
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 13:32

Is it possible to combine the CASE statement and the LIKE operator in a MySQL SELECT statement?

For Example, I am trying to query

相关标签:
4条回答
  • 2021-02-01 13:35

    Assuming the number of digits is constant, you could use something like this:

    SELECT IF(digits > 919999, MOD(digits, 100), MOD(digits, 10000) FROM raw
    

    Add 0's to match your actual number of digits.

    0 讨论(0)
  • 2021-02-01 13:40

    Using the second form of CASE should work:

    SELECT
      CASE
        WHEN digits LIKE '6901%' THEN substr(digits,4)
        WHEN digits LIKE '91%' THEN substr(digits,2)
      END as digits
    FROM raw
    

    Furthermore, you have a stray comma at the end of your SELECT.

    0 讨论(0)
  • 2021-02-01 13:40

    Perhaps use LEFT()?

    SELECT
        CASE 
          WHEN LEFT(digits, 4) = '6901' THEN substr(digits,4)
          WHEN LEFT(digits, 2) = '91' THEN substr(digits,2)
        END 
    FROM raw
    

    Should be more performant than the LIKE.

    0 讨论(0)
  • 2021-02-01 13:54

    Try

    SELECT
        CASE true
          WHEN digits LIKE "6901%" THEN substr(digits,4)
          WHEN digits LIKE "91%" THEN substr(digits,2)
        END as "digits",
    FROM raw
    
    0 讨论(0)
提交回复
热议问题