我想在SQL中将一行拆分成几行。

例如,我有一个“ 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;


对不起,我知道这太基础了。

最佳答案

我相信您可以这样做:

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

关于mysql - 如何将值分成几行(MySQL),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45940508/

10-11 03:31