在这个查询中,我想要返回总共x个记录。在该查询中,我有几个子查询,我不能确定他们是否会返回最大记录数。如果一个结果小于它的最大限制,我想用下一个查询填充剩余的插槽,依此类推。我不能在限制条款中做数学,所以我仍然试图找出如何做到这一点。如果数学在限制条款中可用,我会怎么做。
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
)
答案 0 :(得分: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)
Sqlfiddle: -