Reputation: 10683
I have 2 tables orc_users and orc_files. Now I want to fetch files of related users from orc_files table I have try this Query:-
use orc
select *
from orc_users as T1
INNER JOIN orc_files AS t2 on T1.id = t2.userid
where T1.email='sdfsdf';
and I got this result:-
but I want records something like:-
user={name:"sad",
phone:"asdasda",
files:[{filename:"dfsdfs",size:12,fileid:"sdfs"},
{filename:"dfsdfs",size:12,fileid:"sdfs"}]}
I am using node.js with MySQL so it give me result in array.
please help me. Thanks in advance.
Upvotes: 2
Views: 66
Reputation: 35573
all untested: Use group_concat() for the comma separated string and group by in the query, like so:
select
t1.id
/* specify the fields here */
, GROUP_CONCAT(T2.Filename
ORDER BY T2.Filename ASC SEPARATOR ', ') as filenames
from orc_users as T1
INNER JOIN orc_files AS t2 on T1.id = t2.userid
where T1.email='sdfsdf'
group by
t1.id
/* specify the fields here too */
;
Try also using CONCAT() to get both filename and size, e.g.
, GROUP_CONCAT( CONCAT(T2.Filename,' size:',T2.size)
ORDER BY T2.Filename ASC SEPARATOR ', ') as filenames
If concat() inside the group_concat() works [I think it will] keep adding items until you get all the details required.
performance warning: no idea how well this would perform, might not be great.
Upvotes: 1
Reputation: 4284
There is no possible to get that result in a single query, but you can get files
data in each individual row as query and attach it results into current row.
Upvotes: 0