开发者

how to select 3 random items of each category?

I need some help writing a select query basically I have the table structured as below:

cat_prod
----------
cid | pid
----------
 1 | 1
 2 | 2
 3 | 3
 4 | 4
 5 | 5
 1 | 2
 2 | 3
 3 | 4
 4 | 5
 5 | 1
 1 | 3
 2 | 4
 3 | 5
 4 | 1
 5 | 2


Now I would like to select at least 3 random pid's of each cid where it ex开发者_JAVA百科ists or the maximum pid's if less than 3, how would i do that in one query? Baring in mind I would like the query to be as efficent as possible and that the table data is likely to grow considerablly.

Thanks


Although some changes might be needed, the following query is almost appropriate:

select C.cid, C.pid
from cat_prod C
where C.pid in (select c1.pid from cat_prod c1 order by (pid) limit 3); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜