Can you split/explode a field in a MySQL query?

后端 未结 17 1124
无人及你
无人及你 2020-11-22 04:03

I have to create a report on some student completions. The students each belong to one client. Here are the tables (simplified for this question).

CREATE TAB         


        
17条回答
  •  庸人自扰
    2020-11-22 04:33

    Seeing that it's a fairly popular question - the answer is YES.

    For a column column in table table containing all of your coma separated values:

    CREATE TEMPORARY TABLE temp (val CHAR(255));
    SET @S1 = CONCAT("INSERT INTO temp (val) VALUES ('",REPLACE((SELECT GROUP_CONCAT( DISTINCT  `column`) AS data FROM `table`), ",", "'),('"),"');");
    PREPARE stmt1 FROM @s1;
    EXECUTE stmt1;
    SELECT DISTINCT(val) FROM temp;
    

    Please remember however to not store CSV in your DB


    Per @Mark Amery - as this translates coma separated values into an INSERT statement, be careful when running it on unsanitised data


    Just to reiterate, please don't store CSV in your DB; this function is meant to translate CSV into sensible DB structure and not to be used anywhere in your code. If you have to use it in production, please rethink your DB structure

提交回复
热议问题