Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Joining two tables & group by name

I am trying to write a SQL query where it collects the User info along with UserPhotos. For some reason my query results in returning same user info with a different photo URL.

select * from User as a JOIN UserPhoto as up ON a.ID=up.UserId

Table User

FirstName | LastName |   DOB    | ID
ABC          YZV         123     1234567 
BCD          XYZ         123     1234568 
XYZ          MCD         124     1234569 
MNO          XYZ         125     1234570

Table UserPhoto

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID |   UserId   | PhotoUrl
01    1234567      https://imageUrl1
02    1234567      https://imageUrl2
03    1234568      https://imageUrla1
04    1234568      https://imageUrlb1

Expected output:

{
  fName: "ABC",
  lName: "YZV", 
  dob: 123, 
  id: 1234567, 
  photos {
   https://imageUrl1,
   https://imageUrl2
  }
}

>Solution :

You could group_concat the photos and then join on them:

SELECT u.*, photos
FROM   users u
JOIN   (SELECT   userid, GROUP_CONCAT(photourl ORDER BY photourl ASC) AS photos
        FROM     userphoto
        GROUP BY userid) up ON u.id = up.userid
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading