Is it possible to get the list of rows grouped together by a column name in Mysql?

135 Views Asked by At

In my database, I have a table called 'results' with four columns (name,device,passed,failed). Suppose if there are 4 rows in the table as below.

name   device   passed failed

test1  device_1    2      1
test1  device_2    3      0
test2  device_1    1      2
test2  device_2    2      1

I want the below result:

[(test1,device_1,2,1),(test1,device_2,3,0)]
[(test2,device_1,1,2),(test1,device_2,2,1)]

Is it possible to get that result with only one query to DB?

currently I am querying database twice, first getting a list of distinct names and then getting rows with that name. Below is the pseudo code.

 test_names = SELECT DISTINCT name FROM results
 for test_name in test_names: 
      rows = SELECT * FROM results WHERE name=test_name

then I am processing rows to get the object structure that I wanted.

2

There are 2 best solutions below

0
On
 SELECT GROUP_CONCAT('(',name,',',device,',',passed,',',failed,')') FROM results group by name;
0
On

You need concatenation functions like CONCAT_WS() and CONCAT to concatenate the columns of each row and then aggregation with GROUP_CONCAT() for each name:

SELECT CONCAT('[', GROUP_CONCAT(CONCAT('(', CONCAT_WS(',', name, device, passed, failed), ')')), ']') AS result
FROM results
GROUP BY name

See the demo.