简体   繁体   中英

How to Fetch record from another table which is having multiple record for same id?

I have table structures as follows

table-1
-------
id
name


table-2
--------
imageId
id ( reference of table1.id)
image

and table1 has the following record

id     name 
1      A
2      B
3      C

Table 2 has

imageId      id          image
1             1         image1.jpg
2             1         image2.jpg
3             2         image3.jpg

ie, table1.id has many images in table2, now i need to select the record and its corresponding images(multiple images for same id), like

id   name       image
1     A         image1.jpg,image2.jpg
2     B         image3.jpg
select
    b.imageId,
    a.id,
    b.imageName
from
    table-1 a
    right outer join table-2
        on a.id=b.id

This will give you an output of:

id   name       image

1     A         image1.jpg
1     A         image2.jpg
2     B         image3.jpg

You can use the GROUP_CONCAT function to get values across multiple rows into a single comma-delimited string (such as how you have in your example desired result):

SELECT a.id, a.name, GROUP_CONCAT(b.image) AS images
FROM table1 a
INNER JOIN table2 b ON a.id = b.id
GROUP BY a.id, a.name

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM