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

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

    Based on Alex answer above (https://stackoverflow.com/a/11022431/1466341) I came up with even better solution. Solution which doesn't contain exact one record ID.

    Assuming that the comma separated list is in table data.list, and it contains listing of codes from other table classification.code, you can do something like:

    SELECT 
        d.id, d.list, c.code
    FROM 
        classification c
        JOIN data d
            ON d.list REGEXP CONCAT('[[:<:]]', c.code, '[[:>:]]');
    

    So if you have tables and data like this:

    CLASSIFICATION (code varchar(4) unique): ('A'), ('B'), ('C'), ('D')
    MY_DATA (id int, list varchar(255)): (100, 'C,A,B'), (150, 'B,A,D'), (200,'B')
    

    above SELECT will return

    (100, 'C,A,B', 'A'),
    (100, 'C,A,B', 'B'),
    (100, 'C,A,B', 'C'),
    (150, 'B,A,D', 'A'),
    (150, 'B,A,D', 'B'),
    (150, 'B,A,D', 'D'),
    (200, 'B', 'B'),
    

提交回复
热议问题