mysql选择每种类型的3个随机行

时间:2013-01-08 00:15:20

标签: mysql random

我创建了以下查询:

 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是一张有图片的表格 和援助是专辑ID

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

我希望能够修改查询,这样我就可以为每个专辑ID获得3张随机图片, 所以任何帮助都会受到赞赏。

我也想在cpg_albums表中加入这个最终结果,其中cpg_pictures.aid = cpg_albums.aid

1 个答案:

答案 0 :(得分: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