Can MySQL nested select return list of results

I want to write a mysql statement that will return a list of results from one table along with a comma-separated field from another table. I think an example can better explain this.

Table 1
========================

id First_Name Surname
----------------------
1  Joe       Bloggs
2  Mike      Smith
3  Jane      Doe

Table 2
========================

id Person_Id Job_id
---------------------
1  1         1
2  1         2
3  2         2
4  3         3
5  3         4

I want to return a comma separated list of people job_ids. So my result set will be

id First_Name Surname job_id
------------------------------
1  Joe       Bloggs   1,2
2  Mike      Smith    2
3  Jane      Doe      3,4

I think sql will be something like

select id, First_Name, Surname, (SELECT job_id FROM Table 2) as job_id from Table 1

but obviously this will not work, so you need to change the '(SELECT job_id FROM Table 2) as part of job_id.

Hope this makes sense

Thanks, John

+3
source share
1 answer

You can use the function GROUP_CONCAT()as shown below:

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 me check it with the 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);

Request Result:

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

, GROUP_CONCAT() 1024. . SET, , :

SET GLOBAL group_concat_max_len = 2048;
+6

Source: https://habr.com/ru/post/1738690/


All Articles