简体   繁体   English

使用CakePHP将两个查询合并为一个

[英]Combining two queries into one with CakePHP

I'm working on a photo gallery project. 我正在做一个照片库项目。 I want to list the 20 most recently created albums and also show each of those albums' most recently uploaded photo (if it has one). 我想列出最近创建的20张专辑,并展示这些专辑中最近上传的照片(如果有的话)。 The way I'm doing it now is querying the albums ( $this->Album->find('all', ...) ) and then passing the IDs from those results into my second query, which is the query that finds the most recently uploaded photo for the 20 albums found by the first query. 我现在这样做的方式是查询相册( $this->Album->find('all', ...) )然后将这些结果中的ID传递给我的第二个查询,这是查询的查询最近上传的第一张查询找到的20张相册的照片。

This is what the actual queries look like: 这是实际查询的样子:

SELECT `Album`.`id`, `Album`.`name`, `Album`.`photo_count` FROM `mydb`.`albums` AS `Album` WHERE 1 = 1 ORDER BY `Album`.`created` DESC LIMIT 20

SELECT `Photo`.`album_id`, `Photo`.`name` FROM `mydb`.`photos` AS `Photo` WHERE `Photo`.`album_id` IN (21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2) GROUP BY `Photo`.`album_id` ORDER BY `Photo`.`created` DESC

I don't like doing two queries and that second query looks rather inefficient. 我不喜欢做两个查询,第二个查询看起来效率很低。 Is there a way to make CakePHP do this in one, efficient query? 有没有办法让CakePHP在一个有效的查询中执行此操作?

I think you're looking for the following query which uses a subquery to return the most recent 20 albums, and then JOINs on the photos table to return the photos associated with those albums (replace with LEFT JOIN if needed): 我认为你正在寻找它使用子查询返回最近的20张专辑,然后下面的查询JOINs ,照片上的表返回与这些专辑相关的照片(替换为LEFT JOIN如果需要的话):

SELECT A.Id, A.Name, A.Photo_Count, P.Name
FROM (SELECT * 
      FROM mydb.albums 
      ORDER BY Created DESC 
      LIMIT 20) A 
    INNER JOIN mydb.photos P ON A.Id = P.Album_Id
GROUP BY A.Id 
ORDER BY P.Created DESC

I removed your WHERE statement as I suspect those are the 20 Ids being returned from your Albums table. 我删除了您的WHERE语句,因为我怀疑这些是从您的相册表中返回的20个ID。

EDIT: If I understood your comments correctly, you just need to add A.Created to your main query's ORDER BY clause: 编辑:如果我正确理解你的评论,你只需要将A.Created添加到主查询的ORDER BY子句:

SELECT A.Id, A.Name, A.Photo_Count, P.Name
FROM (SELECT * 
      FROM mydb.albums 
      ORDER BY Created DESC 
      LIMIT 20) A 
    INNER JOIN mydb.photos P ON A.Id = P.Album_Id
GROUP BY A.Id 
ORDER BY A.Created DESC, P.Created

Use ASC and DESC after each field as needed. 根据需要在每个字段后使用ASCDESC

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

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