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

后端 未结 17 1182
无人及你
无人及你 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:34

    You can create a function for this:

    /**
    * Split a string by string (Similar to the php function explode())
    *
    * @param VARCHAR(12) delim The boundary string (delimiter).
    * @param VARCHAR(255) str The input string.
    * @param INT pos The index of the string to return
    * @return VARCHAR(255) The (pos)th substring
    * @return VARCHAR(255) Returns the [pos]th string created by splitting the str parameter on boundaries formed by the delimiter.
    * @{@example
    *     SELECT SPLIT_STRING('|', 'one|two|three|four', 1);
    *     This query
    * }
    */
    DROP FUNCTION IF EXISTS SPLIT_STRING;
    CREATE FUNCTION SPLIT_STRING(delim VARCHAR(12), str VARCHAR(255), pos INT)
    RETURNS VARCHAR(255) DETERMINISTIC
    RETURN
        REPLACE(
            SUBSTRING(
                SUBSTRING_INDEX(str, delim, pos),
                LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1
            ),
            delim, ''
        );
    

    Converting the magical pseudocode to use this, you would have:

    SELECT e.`studentId`, SPLIT_STRING(',', c.`courseNames`, e.`courseId`)
    FROM...
    

提交回复
热议问题