1

このクエリでは、合計 x 個のレコードが返されます。そのクエリ内には、最大数のレコードを返すかどうかわからないサブクエリがいくつかあります。1 つの結果が最大制限未満の場合は、残りのスロットに次のクエリなどを入力します。limit 節の中で計算できないので、どうやって計算するかまだ模索中です。limit 句内で数学が利用可能である場合、私は次のようにします。

select *
from 
(
(select * from profile where size='local' order by rand() limit 7) as local 
join 
(select * from profile where size='regional' order by rand() limit (13-count(local.id)) as regional
join 
(select * from profile where size='national' order by rand() limit (19-(count(local.id)+count(regional.id))) as national
join 
(select * from profile where size='international' order by rand() limit (25-(count(local.id)+count(regional.id)+count(national.id)))) as international    
)
4

1 に答える 1

1

私はこれを不必要に複雑な方法で行ったかもしれませんが、うまくいくようです:-

SELECT id, size
FROM
(
    SELECT id, size, 
        @SeqLocal:=IF(size="local", IF(@SeqLocal <= 7, @SeqLocal + 1, @SeqLocal), @SeqLocal) AS SeqLocal,
        @SeqRegional:=IF(size="regional", IF(@SeqLocal + @SeqRegional <= 14, @SeqRegional + 1, @SeqRegional), @SeqRegional) AS SeqRegional,
        @SeqNational:=IF(size="national", IF(@SeqLocal + @SeqRegional + @SeqNational <= 21 , @SeqNational + 1, @SeqNational), @SeqNational) AS SeqNational,
        @SeqInternational:=IF(size="international", IF(@SeqLocal + @SeqRegional + @SeqNational + @SeqInternational <= 28, @SeqInternational + 1, @SeqInternational), @SeqInternational) AS SeqInternational
    FROM
    (
        select *
        from profile 
        where size IN ("local", "regional", "national", "international")
        order by FIELD(size, "local", "regional", "national", "international"), rand() 
    ) Sub1
    CROSS JOIN (SELECT @SeqLocal:=0, @SeqRegional:=0, @SeqNational:=0, @SeqInternational:=0) Sub2
) Sub3
WHERE (size = "local" AND SeqLocal != @SeqLocal)
OR  (size = "regional" AND SeqRegional != @SeqRegional)
OR  (size = "national" AND SeqNational != @SeqNational )
OR  (size = "international" AND SeqInternational != @SeqInternational)

ここでSqfiddle:-

http://www.sqlfiddle.com/#!2/cc3b884/14

于 2013-11-08T20:37:49.127 に答える