从每个类别中随机获取5行,其中主表和类别表具有一对多关系

时间:2012-12-15 13:54:04

标签: php mysql join

这是我有两张桌子的情况

of
    idof, (somtother data)
    ---------------------
    1, (somtother data)
    2, (somtother data)
    3, (somtother data)

我有

ofc
    id, ofid, idcat
    ------------------
    1,1,1
    1,1,2
    1,2,1
    1,3,3

以下是我用来从第一张表中获取所有内容并将其与第二张相关联的内容

SELECT * FROM `of` 
    LEFT JOIN (`ofc`) 
    ON ( `of`.`idof` = `ofc`.`ofid` )

现在我想从每个idcat获得5行(想象第二个表有更多行),我似乎无法使sql正确。我到现在为止已经完成了

select * from `of` as `f` 
    JOIN `ofc` as `fa` 
    ON `f`.`idof`=`fa`.`ofid`
where (
    select count(*) from `of` as `nf` 
    JOIN `ofc` as `nfa` 
    ON `nf`.`idof`=`nfa`.`ofid` 
    GROUP BY `nfa`.`idcat`
) <= 5;

这个子查询返回多行,而mysql抱怨。有没有其他方法可以做到这一点?没有为每个不同的idc执行一个查询?

0 个答案:

没有答案