mysql select odd number values in a column that includes delimiter separated values

你离开我真会死。 提交于 2020-01-06 05:31:09

问题


My next database table will be set up more optimally. Unfortunately this one was already set up where one column [data] contains checkbox array values that were saved the following way:

value 1|~|value 1 value 2|~|value 2 value 3|~|value 3

Not optimal, I know. What I need is a mysql query that select only the values in [data] column in front of the |~|. Basically think I need to select the only odd values.

Any help pointing me in the right direction is greatly appreciated. I tried an if statement in a query and it did not work. Of course I deleted that by mistake.


回答1:


What I need is a mysql query that select only the values in [data] column in front of the |~|.

One thing to note the numbers before |~| must be unique.
It will not show the same number twice.

Query

SELECT
 DISTINCT 
   SUBSTRING (
       record_data.column
     , LOCATE('|~|', record_data.`column` , number_generator.number) - 1
     , 1
   ) AS number
FROM (
  SELECT 
   @row := @row + 1 AS number
  FROM (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) record_1
  CROSS JOIN (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) record_2    
  CROSS JOIN (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) record_4
  CROSS JOIN (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) record_5     
  CROSS JOIN (
    SELECT @row := 0 
  ) AS init_user_params
) AS number_generator

CROSS JOIN (


SELECT 
 *
FROM (
  SELECT 'value 1|~|value 1 value 2|~|value 2 value 3|~|value 3' AS `column`
) AS record 

) AS record_data

WHERE
   LOCATE('|~|', record_data.`column` , number_generator.number) <> 0

Result

| number |
| ------ |
| 1      |
| 2      |
| 3      |

demo



来源:https://stackoverflow.com/questions/53120298/mysql-select-odd-number-values-in-a-column-that-includes-delimiter-separated-val

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