如何在几行中拆分值(MySQL)

问题描述 投票:0回答:4

我想在SQL中分几行分成几行。

例如,我有'A ADCT DROP INCALL - ',它包含空格和' - ',我希望例如在几行中值保持分开。

原始结果:

SELECT statuses FROM campaigns;
+-----------------------------------------+
| RESULT OF QUERY                         |
+-----------------------------------------+
| A ADCT DROP INCALL -                    |
+-----------------------------------------+

结果必须如下:

+-----------------------------------------+
| RESULT OF QUERY                         |
+-----------------------------------------+
| A                                       |
| ADCT                                    |
| DROP                                    |
| INCALL                                  |
+-----------------------------------------+

我尝试使用SUBSTRING_INDEX:

SELECT status
FROM statuses
WHERE statuses.status NOT IN (SELECT SUBSTRING_INDEX(TRIM(dial_statuses)," ", 1) FROM campaigns WHERE campaign_id = '4000')
ORDER BY STATUS;

对不起,我知道那是基本的。

mysql sql split substring
4个回答
0
投票

我相信你可以这样做:

SELECT
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) 
  name
FROM
  numbers 
INNER JOIN tablename ON CHAR_LENGTH(tablename.name)
 -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
ORDER BY
  id, n

请参阅小提琴here

如果您无法创建表,那么解决方案可以是:

SELECT
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) 
  name
FROM
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers 
INNER JOIN tablename ON CHAR_LENGTH(tablename.name)
 -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
ORDER BY
  id, n

一个例子小提琴是here


0
投票

您可以尝试在MySQL中创建函数,如下所示:

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
   LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
   delim, '');

然后你应该能够在查询中使用它:

SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;

这是未经测试但应该有效。有关更多信息,请查看this


0
投票

如果我正确读到这个,那么这个问题已经被问到here

SQL split values to multiple rows

答案从@fthiella说明如下:

select
tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

查看一个工作示例here

http://sqlfiddle.com/#!9/ffa86a/1


0
投票

如果你只需要替换空格 - 那么你可以使用

SELECT TRIM(两个“\ n”FROM REPLACE(REPLACE(column_name,'',“\ n”),“ - ”,“\ n”))FROM table;

如果您想要从开头和结尾开始前导或尾随空格,可以从上面的语句中跳过trim。

© www.soinside.com 2019 - 2024. All rights reserved.