Can MySQL Nested Select return list of results

前端 未结 1 1019
日久生厌
日久生厌 2020-12-17 05:01

I want to write a mysql statement which will return a list of results from one table along with a comma separated list of field from another table. I think an example might

相关标签:
1条回答
  • 2020-12-17 05:44

    You may want to use the GROUP_CONCAT() function, as follows:

    SELECT    t1.id, 
              t1.first_name, 
              t1.last_name,
              GROUP_CONCAT(DISTINCT job_id ORDER BY job_id SEPARATOR ',') job_id
    FROM      Table1 t1
    JOIN      Table2 t2 ON (t2.Person_id = t1.id)
    GROUP BY  t1.id;
    

    Let's test it with your example data:

    CREATE TABLE Table1 (
        id int AUTO_INCREMENT PRIMARY KEY, 
        first_name varchar(50), 
        last_name varchar(50));
    
    CREATE TABLE Table2 (
        id int AUTO_INCREMENT PRIMARY KEY, 
        person_id int,
        job_id int);
    
    INSERT INTO Table1 VALUES (NULL, 'Joe', 'Bloggs');
    INSERT INTO Table1 VALUES (NULL, 'Mike', 'Smith');
    INSERT INTO Table1 VALUES (NULL, 'Jane', 'Doe');
    
    INSERT INTO Table2 VALUES (NULL, 1, 1);
    INSERT INTO Table2 VALUES (NULL, 1, 2);
    INSERT INTO Table2 VALUES (NULL, 2, 2);
    INSERT INTO Table2 VALUES (NULL, 3, 3);
    INSERT INTO Table2 VALUES (NULL, 3, 4);
    

    Result of the query:

    +----+------------+-----------+--------+
    | id | first_name | last_name | job_id |
    +----+------------+-----------+--------+
    |  1 | Joe        | Bloggs    | 1,2    | 
    |  2 | Mike       | Smith     | 2      | 
    |  3 | Jane       | Doe       | 3,4    | 
    +----+------------+-----------+--------+
    

    Note that by default, the result of GROUP_CONCAT() is truncated to the maximum length of 1024. However this can be set to a much larger value. Use the SET command if you require to modify it, as follows:

    SET GLOBAL group_concat_max_len = 2048;
    
    0 讨论(0)
提交回复
热议问题