简体   繁体   中英

MySQL query select rows from A and combine multiple rows from B

After looking into this, apparently it's a complex thing to do? It doesn't look like it's a pivot query, or should it be?? Anyway, two tables like this:

articles:

id    col2    col3
 1    ....    ....
 2    ....    ....
 3    ....    ....

articleImages:

id    imgFile    artRef
 1    img1.jpg   1
 2    img2.jpg   1
 3    img3.jpg   2
 4    .......    3
 5    .......    3
 6    .......    3

I want to select everything form "articles" and combine the "articleImages" into the row so it will look something like this:

[{
    "id":"1",
    "col2":"...",
    "col3":"...",
    "imgFiles":{
        "img1.jpg",
        "img2.jpg"
    }
  },{
    "id":"2",
    "col2":"...",
    "col3":"...",
    "imgFiles":{
        "img3.jpg"
    }
  },{
    "id":"3",
    ...etc.
}]

I tried:

"SELECT art.*, ai.imgFile FROM articles art LEFT JOIN articleImages ai ON art.id = ai.artRef ORDER BY art.id desc LIMIT $lim, $limit"

And that's wrong...I got separate rows for each image. It's not a LEFT JOIN ...what's the syntax for this? Or is there a more optimal way of organizing the table? I didn't want to make an "articleImages" column and concatenate inside "articles"...

If I got your goal correctly you can group your query and use GROUP_CONCAT function to get all coma separated img names in one field:

SELECT art.*, 
       GROUP_CONCAT(ai.imgFile) imgFiles
FROM articles art 
LEFT JOIN articleImages ai 
ON art.id = ai.artRef 
GROUP BY art.id
ORDER BY art.id desc 
LIMIT $lim, $limit

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