Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database to return multi-dimensional result

This is a follow-up question to my previous one.
Situation:

Table 1:
+--------------------+--------------------+
|               v_id |             v_name |
+--------------------+--------------------+
|                  1 |            v_name1 |
+--------------------+--------------------+
| etc...

Table 2:
+--------------------+--------------------+
|               a_id |             a_name |
+--------------------+--------------------+
|                  1 |            a_name1 |
+--------------------+--------------------+
| etc...

Table 3:
+--------------------+--------------------+
|               v_id |               a_id |
+--------------------+--------------------+
|                  1 |                  1 |
+--------------------+--------------------+
|                  1 |                  2 |
+--------------------+--------------------+
|                  1 |                  3 |
+--------------------+--------------------+

I want to get a join of the two tables:

SELECT t1.*, t2.a_name
FROM `table1` t1
LEFT JOIN `table_3` t3 ON t3.v_id = t1.v_id
LEFT JOIN `table_2` t2 ON t2.a_id = t3.a_id
WHERE t1.id = 1;

The result of this query will be 3 rows for the given tables, each row with the same values from Table 1, just a different a_name from Table 3.
Now, is it possible for me to make a_name an array (of 3 cells in this case)? I think that this is not possible. If it's not, how would I have to build the query so that it would return just one row, with the a_name results joined with a given 'glue' string?


EDIT If I were to get a result in PHP, I would expect something like:

$result = array(
    'v_id'    => 1,
    'a_name'  => array('a_name1', 'a_name2', 'a_name3')
);

or

$result = array(
    'v_id'    => 1,
    'a_name'  =>'a_name1, a_name2, a_name3'), # assuming I used ', ' as the glue string
);
like image 467
Michal M Avatar asked Mar 09 '26 02:03

Michal M


1 Answers

I believe you are looking for the GROUP_CONCAT function.

In your query it would look like this:

SELECT t1.*, GROUP_CONCAT(t2.a_name SEPARATOR ',')
FROM `table1` t1
LEFT JOIN `table_3` t3 ON t3.v_id = t1.v_id
LEFT JOIN `table_2` t2 ON t2.a_id = t3.a_id
WHERE t1.id = 1
GROUP BY [list of t1 columns here] 
-- update thanks to OMG Ponies.
like image 79
Sean Vieira Avatar answered Mar 10 '26 16:03

Sean Vieira