Question

In the hypothetical scenario where I have a couple of database tables, in a one to many relationship. I am trying to find a nice query function so that I can return each row in table A with a nested array for all the linked rows from table B.

SELECT a.id AS id,a.name as name,b.id AS b_id,b.name AS b_name FROM a,b WHERE a.id=b.eid;

will return only one result

SELECT 
    a.id AS id,
    a.name as name,
    GROUP_CONCAT(b.id) AS b_id,
    GROUP_CONCAT(b.name) AS b_name 
FROM a,b 
WHERE a.id = b.eid;

whereas this returns what I want but I'm after an array not a string (there might be commas in b.name)

What am I missing?

Was it helpful?

Solution

You can use separator different from comma:

GROUP_CONCAT(b.name SEPARATOR ';') AS b_name

OTHER TIPS

It isn't possible to return anything other than a MySQL datatype, so the short answer is no you cannot return a array (nested or otherwise) of results from a subquery. You'll also see some pretty drastic performance hits trying to build string concatenated values from the foreign, the sub-string order will be implicit and, as you've alluded to, you'll have problems selecting a suitable delimiter.

It almost certainly going to be more efficient use a simple JOIN to create a single result set. Any duplicates on the "one" side of the relationship should be handled programmatically (which is preferable, in any sense, to handling string splitting on multiple concatenated fields).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top