I need to join tables and fetch output as single array in single query, even though a user has multiple address
My query:
SELECT user.name, address.address, user.place
FROM user
LEFT JOIN address
WHERE user.user_id = address.user_id
GROUP BY user.name, address.address, user.place
Suppose a user has multiple address am currently getting output as two rows.Is there any way to collect all output values in a single array using single query.
Please help.
You can use group_concat
in your query.
SELECT user.name, group_concat(address.address) as 'address', user.place
FROM user
LEFT JOIN address
WHERE user.user_id = address.user_id
Another way is to use FOR XML statement:
SELECT DISTINCT
u.name,
STUFF((SELECT ';' + a.[address]
FROM address a
WHERE u.[user_id] = a.[user_id]
FOR XML PATH('')),1,1,'') as [address],
u.place
FROM [user] u
Output will be like:
name address place
Mike adr1;adr2;adr3 someplace
Try FOR XML PATH('') , it will join you addresses in one row:
select
[user].[name],
(select [address] + ', '
from [address]
where
[user_id] = [user].[user_id]
for xml path('')),
user.place
from [user]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.