0

My csv column in mytable contains the following content as TEXT column.

john;doe;12;john@example.com

I want to create a view, but would prefer the resulting table being varchar columns. But instead, I'm getting TEXT with the following select:

CREATE VIEW my_view AS
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(csv, ';', 2), ';', -1) AS test
FROM mytable;

Is it impossible to convert those fields to varchar or char?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • ["Is storing a delimited list in a database column really that bad?"](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad?r=SearchResults&s=1|177.7861) – sticky bit Feb 05 '20 at 13:08

1 Answers1

1

But instead, I'm getting TEXT

Where you have taken this info from?

CREATE TABLE mytable (csv VARCHAR(250))
SELECT 'john;doe;12;john@example.com' AS csv;
CREATE VIEW my_view AS
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(csv, ';', 2), ';', -1) AS test
FROM mytable;
CREATE TABLE test
SELECT * FROM my_view;
SHOW CREATE TABLE test;
Table | Create Table                                                                                                                     
:---- | :------------------------------------------------------------------
test  | CREATE TABLE `test` (
      |   `test` varchar(250) DEFAULT NULL
      | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

db<>fiddle here


I forgot to mention that the csv field is of type TEXT

If so explicit convertion needed.

CREATE TABLE mytable (csv TEXT)
SELECT 'john;doe;12;john@example.com' AS csv;
CREATE VIEW my_view AS
SELECT CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(csv, ';', 2), ';', -1), CHAR(255)) AS test
FROM mytable;
CREATE TABLE test
SELECT * FROM my_view;
SHOW CREATE TABLE test;
Table | Create Table                                                                                                                     
:---- | :------------------------------------------------------------------
test  | CREATE TABLE `test` (
      |   `test` varchar(255) DEFAULT NULL
      | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

db<>fiddle here

Akina
  • 39,301
  • 5
  • 14
  • 25