doujiao1981 2013-04-09 17:43
浏览 30
已采纳

如何修改此MySQL查询以获取特定的数据结构?

If I have two simple tables:

Photos :

photoid | filename            | albumid
1       | something.jpg       |    1
2       | somethingelse.jpg   |    1

And an Albums table :

  albumid   | album_name        | owner_id
    1       | My Holiday 2012   |    1
    2       | My Holiday 2013   |    6

And I want to get all photos contained within all albums for a given owner_id

I can do the following :

select albums.*, photos.*
from photo_albums as albums
left join photos as photos
on albums.albumid = photos.albumid
where albums.owner_id = :owner_id

This will return 2 rows, on for each photo as well as the relevant album data.

However what I would like to do is return only on row per album. With the photos rows nested within each album row.

Returning output similar to the following:

[{
    albumid : 1,
    album_name : My Holiday 2012,
    owner_id : 1,
    photos : {
                 photoid : 1,
                 filename : something.jpg
             },
             {
                 photoid : 2,
                 filename : somethingelse.jpg
             }   
}]

Is there an easy and efficient way to do this within the MySQL query itself? If so how? Or alternatively am I better taking the complete row data from the original query and constructing the data into this output by looping through the rows in php?

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dsxmwin86342 2013-04-09 17:48
    关注

    You just can't do it by modifying SQL query.

    I see two ways to achieve your goal:

    1. Postprocess your output to build needed array structure.
    2. Use a ORM (Object-relational mapping) to automatically map your query results to objects. For example, see Doctrine.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退