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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路