2013-01-08 64 views
2

我創建了下面的查詢行:MySQL的選擇3個隨機每種類型的

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表

這個查詢將獲得1張隨機圖片從每個相冊ID,

我想能夠修改查詢,所以我可以得到3個隨機圖片爲每個專輯ID 所以任何幫助,將不勝感激。

我也想加入與在cpg_pictures.aid = cpg_albums.aid

回答

0

你試過這個cpg_albums表這個最終的結果?

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 

您還可以模擬1和本http://beyondrelational.com/modules/2/blogs/70/posts/10845/return-top-n-rows.aspx

2