MySQL查询从A中选择行并从B中合并多行


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

在研究了这个之后,显然这是一件复杂的事情?它看起来不像一个pivot查询,或者应该是吗?总之,像这样的两个表:

的文章:

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

我想选择"articles"的所有内容,并将"articleImages"合并到行中,使其看起来像这样:

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

我试着:

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

这是错误的…每个图像都有单独的行。这不是LEFT JOIN…这个的语法是什么?还是有更理想的方式来安排餐桌?我不想做一个"articleImages"列,并在"articles"中连接…

如果我得到你的目标正确,你可以组你的查询和使用GROUP_CONCAT函数得到所有逗号分隔img名称在一个字段:

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