简体   繁体   English

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

[英]How can I modify this MySQL query to get a particular data structure?

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 我想获取给定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. 对于每张照片以及相关的相册数据,这将返回2行。

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? 在MySQL查询本身中,是否有一种简单有效的方法来执行此操作? 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? 或者,我是否更好地从原始查询中获取完整的行数据,并通过遍历php中的行将数据构造到此输出中?

Thanks in advance 提前致谢

You just can't do it by modifying SQL query. 您只是无法通过修改SQL查询来做到这一点。

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. 使用ORM (对象关系映射)将查询结果自动映射到对象。 For example, see Doctrine . 例如,请参阅“教义”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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