MySQL Case in Select Statement with LIKE operator

青春壹個敷衍的年華 提交于 2019-12-02 19:53:56

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.

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

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.

Joshua Martell

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!