2

我创建了以下查询:

 SELECT random.aid, random.rand_pid, r3.filepath, r3.filename, r3.pid
 FROM 
 (SELECT r.aid,
    (SELECT r2.pid
     FROM cpg_pictures r2
     WHERE r2.aid = r.aid
     ORDER BY RAND() LIMIT 1) AS 'rand_pid'
 FROM cpg_pictures r
 GROUP BY r.aid
 ORDER BY r.aid DESC
 LIMIT 10
 ) random
 LEFT JOIN cpg_pictures AS r3 ON r3.pid = rand_pid

cpg_pictures 是一个包含图片的表,aid 是专辑 ID

此查询将从每个相册 id 中获取 1 张随机图片,

我希望能够修改查询,以便我可以为每个专辑 ID 获取 3 张随机图片,因此我们将不胜感激。

我还想将这个最终结果与 cpg_albums 表结合起来,其中 cpg_pictures.aid = cpg_albums.aid

4

1 回答 1

0

你试过这个吗?

 SELECT random.aid, random.rand_pid, r3.filepath, r3.filename, r3.pid
 FROM 
 (SELECT r.aid,
    (SELECT r2.pid
     FROM cpg_pictures r2
     WHERE r2.aid = r.aid
     ORDER BY RAND() LIMIT 1) AS 'rand_pid'
 FROM cpg_pictures r
 GROUP BY r.aid
 ORDER BY r.aid DESC
 LIMIT 10
 ) random
 LEFT JOIN cpg_pictures AS r3 ON r3.pid = rand_pid

您还可以模拟此http://beyondrelational.com/modules/2/blogs/70/posts/10845/return-top-n-rows.aspx的 1 和 2

于 2013-01-08T08:05:58.117 回答